Python Comprehension

From Exterior Memory
Jump to: navigation, search

Python has very readable list and dict generators, called comprehensions:


l = [item for item in sequence]

Or combined with a filter:

l = [item for item in sequence if item > 1]


d = {key: value for (key, value) in sequence}

Dict comprehension is supported since Python 2.7. If Python 2.6 support is required, use the following syntax:

d = dict((key, value) for (key, value) in sequence)