Created
May 28, 2011 11:18
-
-
Save gennad/996800 to your computer and use it in GitHub Desktop.
List compr, generators and yield
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
mylist = [x*x for x in range(3)] | |
for i in mylist : | |
print(i) | |
# Generators can be read only once | |
mygenerator = (x*x for x in range(3)) | |
for i in mygenerator : | |
print(i) | |
Yield is a keyword that is used like return, except the function will return a generator. | |
def createGenerator() : | |
mylist = range(3) | |
for i in mylist : | |
yield i*i | |
mygenerator = createGenerator() # create a generator | |
print(mygenerator) # mygenerator is an object ! | |
# <generator object createGenerator at 0xb7555c34> | |
for i in mygenerator: | |
print(i) | |
# 0 | |
# 1 | |
# 4 | |
""" | |
To master yield, you must understand that when you call the function, the code you have written in the function body does not run. The function only returns the generator object, this is bit tricky :-) | |
Then, your code will be run each time the for uses the generator. | |
Now the hard part : | |
The first time your function will run, it will run from the beginning until it hits yield, then it'll return the first value of the loop. Then, each other call will run the loop you have written in the function one more time, and return the next value, until there is no value to return. | |
The generator is considered empty once the function runs but does not hit yield anymore. It can be because the loop had come to ends, or because you do not satisfy a "if/else" anymore. | |
""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment