Skip to content

Instantly share code, notes, and snippets.

@jiphex
Last active November 5, 2015 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jiphex/b9c432491e22bb38ef97 to your computer and use it in GitHub Desktop.
Save jiphex/b9c432491e22bb38ef97 to your computer and use it in GitHub Desktop.
How Python generators work
def x(items):
print('before loop')
for x in items:
print ('before yield')
yield "xx %s yy" % x
print('after yield')
print('after loop')
for i in x(list((1,2,3,4))):
print "zz %s aa" % i
[user@computer]$ python generators.py
before loop
before yield
zz xx 1 yy aa
after yield
before yield
zz xx 2 yy aa
after yield
before yield
zz xx 3 yy aa
after yield
before yield
zz xx 4 yy aa
after yield
after loop
@jiphex
Copy link
Author

jiphex commented Nov 5, 2015

At yield(), the generator emits the value yield()ed, then waits for the next iterator call, when the code resumes immediately after the previous call to yield()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment