Python List Comprehensions

Python List Comprehensions

A lightning talk on Python list comprehensions for Grow Beyond with Google.

1b0ab2500efc1b91424fb49045312929?s=128

Yos Riady

August 06, 2013
Tweet

Transcript

  1. Python List Comprehensions

  2. ‘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!
  3. 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]
  4. Thanks!