Skip to content

Instantly share code, notes, and snippets.

@manjuraj
Created January 6, 2012 08:17
Show Gist options
  • Save manjuraj/1569647 to your computer and use it in GitHub Desktop.
Save manjuraj/1569647 to your computer and use it in GitHub Desktop.
List Comprehension in Python (listcomps)
# Notes:
# List comprehension (listcomps) is an expression.
# With list comprehension, you get back a list, not a generator.
# With generator expression, you get back an iterator that computes values as an when needed.
# prints [1, 2, 3, 4]
[x for x in (1, 2, 3, 4)]
# prints [2, 4]
[x for x in (1, 2, 3, 4) if x % 2 == 0]
# prints [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b'), (3, 'a'), (3, 'b'), (4, 'a'), (4, 'b')]
[(x, y) for x in (1, 2, 3, 4) for y in ['a', 'b']]
# prints [(2, 'b'), (4, 'b')]
[(x, y) for x in (1, 2, 3, 4) if x % 2 == 0 for y in ['a', 'b'] if y == 'b']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment