Python Comprehension

From Exterior Memory
Revision as of 20:42, 4 May 2014 by MacFreek (Talk | contribs) (Created page with "Python has very readable list and dict generators, called comprehensions: === List === l = [item for item in sequence] Or combined with a filter: l = [item for item in s...")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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

List

l = [item for item in sequence]

Or combined with a filter:

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

Dict

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)