Writing Efficient Python Code
Logan Thomas
Scientific Software Technical Trainer, Enthought
list, tuple, set, dict, and othersprint(), len(), range(), round(), enumerate(), map(), zip(), and othersos, sys, itertools, collections, math, and othersExplicitly typing a list of numbers
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Using range() to create the same list
# range(start,stop)
nums = range(0,11)
nums_list = list(nums)
print(nums_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# range(stop)
nums = range(11)
nums_list = list(nums)
print(nums_list)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Using range() with a step value
even_nums = range(2, 11, 2)
even_nums_list = list(even_nums)
print(even_nums_list)
[2, 4, 6, 8, 10]
Creates an indexed list of objects
letters = ['a', 'b', 'c', 'd' ]
indexed_letters = enumerate(letters)
indexed_letters_list = list(indexed_letters)
print(indexed_letters_list)
[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
Can specify a start value
letters = ['a', 'b', 'c', 'd' ]
indexed_letters2 = enumerate(letters, start=5)
indexed_letters2_list = list(indexed_letters2)
print(indexed_letters2_list)
[(5, 'a'), (6, 'b'), (7, 'c'), (8, 'd')]
Applies a function over an object
nums = [1.5, 2.3, 3.4, 4.6, 5.0]
rnd_nums = map(round, nums)
print(list(rnd_nums))
[2, 2, 3, 5, 5]
map() with lambda (anonymous function)
nums = [1, 2, 3, 4, 5]
sqrd_nums = map(lambda x: x ** 2, nums)
print(list(sqrd_nums))
[1, 4, 9, 16, 25]
Writing Efficient Python Code