Created
January 6, 2012 08:17
-
-
Save manjuraj/1569647 to your computer and use it in GitHub Desktop.
List Comprehension in Python (listcomps)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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