Skip to content

Instantly share code, notes, and snippets.

@manjuraj
Created January 6, 2012 08:20
Show Gist options
  • Save manjuraj/1569657 to your computer and use it in GitHub Desktop.
Save manjuraj/1569657 to your computer and use it in GitHub Desktop.
Generators in Python (genexps)
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