Last active
November 5, 2015 10:50
-
-
Save jiphex/b9c432491e22bb38ef97 to your computer and use it in GitHub Desktop.
How Python generators work
This file contains hidden or 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 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 |
This file contains hidden or 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
[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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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()