Created
January 6, 2012 08:20
-
-
Save manjuraj/1569657 to your computer and use it in GitHub Desktop.
Generators in Python (genexps)
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
def gen(num): | |
n = 0 | |
while n < num: | |
yield n | |
n += 1 | |
# returns a generator object | |
g = gen(3) | |
# returns 0 | |
g.next() | |
# returns 1 | |
g.next() | |
# returns 2 | |
g.next() | |
# raise StopIteration | |
g.next() | |
# prints 0 1 2 | |
for i in gen(3): | |
print i | |
# Turn a list comprehension into a generator expression by replacing the | |
# square brackets ("[ ]") with parentheses. | |
doubles = (2 * n for n in xrange(3)) | |
for i in doubles: | |
# prints 0 2 4 | |
print i |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment