List Comprehensions

List handling

  • Many programs involve a significant amount of list manipulation.
  • Common problem: constructing new lists from an existing list
     s = [ "3", "4", "10", "11", "12"]
     t = [ ]
     for n in s:
         t.append(int(n))

map(func,s)

  • Previous versions provided map() function
     s = [ "3", "4", "10", "11", "12"]
     t = map(int,s)

List comprehensions

  • A convenient syntax for creating new lists from existing sequences
     s = [ "3", "4", "10", "11", "12"]
     t = [int(x) for x in s]
<<< O'Reilly OSCON 2001, New Features in Python 2, Slide 11
July 26, 2001, beazley@cs.uchicago.edu
>>>