$30 off During Our Annual Pro Sale. View Details »

Python List Comprehensions

Yos Riady
August 06, 2013

Python List Comprehensions

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

Yos Riady

August 06, 2013
Tweet

More Decks by Yos Riady

Other Decks in Programming

Transcript

  1. ‘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!
  2. 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]