Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

python what does yield do


To understand what yield does, you must understand what generators are. And before you can understand generators, you must understand iterables.
Iterables

When you create a list, you can read its items one by one. Reading its items one by one is called iteration:

>>> mylist = [1, 2, 3]
>>> for i in mylist:
...    print(i)
1
2
3

mylist is an iterable. When you use a list comprehension, you create a list, and so an iterable:

>>> mylist = [x*x for x in range(3)]
>>> for i in mylist:
...    print(i)
0
1
4

Everything you can use "for... in..." on is an iterable; lists, strings, files...

These iterables are handy because you can read them as much as you wish, but you store all the values in memory and this is not always what you want when you have a lot of values.
Generators

Generators are iterators, a kind of iterable you can only iterate over once. Generators do not store all the values in memory, they generate the values on the fly:

>>> mygenerator = (x*x for x in range(3))
>>> for i in mygenerator:
...    print(i)
0
1
4

It is just the same except you used () instead of []. BUT, you cannot perform for i in mygenerator a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end calculating 4, one by one.
Yield

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

Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once.

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 a bit tricky :-)

Then, your code will continue from where it left off each time for uses the generator.

Now the hard part:

The first time the for calls the generator object created from your function, it will run the code in your function from the beginning until it hits yield, then it'll return the first value of the loop. Then, each subsequent call will run another iteration of the loop you have written in the function and return the next value. This will continue until the generator is considered empty, which happens when the function runs without hitting yield. That can be because the loop has come to an end, or because you no longer satisfy an "if/else".
Comment

yield python

#"yield" returns a value continues the execution of the function
#"return" returns a value and terminates the execution of the function
Comment

python yield from

# In python construction 'yield from something' is just 
# the abbreviation of 'for i in something: yield i'
# So, we can change this:
def yieldOnly():
    yield "A"
    yield "B"
    yield "C"

def yieldFrom():
    for _ in [1, 2, 3]:
        yield from yieldOnly()

test = yieldFrom()
for i in test:
    print(i)
    
# to this:

def yieldOnly():
    yield "A"
    yield "B"
    yield "C"

def yieldFrom():
    for _ in [1, 2, 3]:
        for i in yieldOnly():
            yield i

test = yieldFrom()
for i in test:
    print(i)
Comment

Yield Expressions in python

yield_atom       ::=  "(" yield_expression ")"
yield_expression ::=  "yield" [expression_list | "from" expression]


#Using the yield operation in functions
def gen():  # defines a generator function
    yield 123

async def agen(): # defines an asynchronous generator function
    yield 123
Comment

python yield from

def iter_wrapper(iterator):
    for i in iterator:
    	yield i

def iter_wrapper(iterator):
    yield from iterator
Comment

PREVIOUS NEXT
Code Example
Python :: variables in python 
Python :: merge sorting algorithm 
Python :: convert python code to pseudocode online 
Python :: python looping through a list 
Python :: pyhon sort a list of tuples 
Python :: download gzip file python 
Python :: python size of set 
Python :: array sort in python 
Python :: python list to arguments 
Python :: format datetime python pandas 
Python :: remove item in dict 
Python :: python incrémentation 
Python :: how to use str() 
Python :: matrix multiplication python without numpy 
Python :: python 3.8 release date 
Python :: python programming language 
Python :: pycryptodome rsa encrypt 
Python :: comparison python 
Python :: groupby as_index=false 
Python :: python list remove 
Python :: pandas set index 
Python :: python randint with leading zero 
Python :: replace NaN value in pandas data frame with zeros 
Python :: dataframe python diplay 2 tables on same line 
Python :: Python - Comment vérifier une corde est vide 
Python :: when to use python sets 
Python :: pomodoro timer in python 
Python :: comment on inclut date et heure en python svp 
Python :: PyQt5 change keyboard/tab behaviour in a table 
Python :: py3-env.bat 
ADD CONTENT
Topic
Content
Source link
Name
1+5 =