python list comprehensions
TRANSCRIPT
Python List Comprehensions
‘Traditional’ way
Constructing a list of squares of even numbers:squares_of_evens = []
# range(10) -> [0,1,2,3,4,5,6,7,8,9]
for n in range(10):
if n%2==0:
squares_of_evens.append(n*n)
print squares_of_evens #[0, 4, 16, 36, 64]
It works - but ugly and slow!
Construct lists in a concise way
General syntax: new_list = [new_item for item in input_list]
new_list = [new_item for item in input_list if some_condition]
Squares of even numbers: squares_of_evens = [n*n for n in range(10) if (n%2 == 0)]
print squares_of_evens #[0, 4, 16, 36, 64]
Thanks!