python list comprehensions

4

Click here to load reader

Upload: yos-riady

Post on 14-Apr-2017

33 views

Category:

Software


0 download

TRANSCRIPT

Page 1: Python List Comprehensions

Python List Comprehensions

Page 2: 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!

Page 3: Python List Comprehensions

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]

Page 4: Python List Comprehensions

Thanks!