Yield — Generators in Python
A generator in python is used to create iterable objects.
You might not hear about yield
, but you must know about return
and use it frequently during development. In fact, yield is similar to return and if you know how to use return, you will know how to use yield in a very short time!
The difference between these two is that while return
terminates a function entirely, yield
pauses the function and saving all its states, continues the function by successive calls.
Let’s see how it works by code
Create a function that will always add 10 from the original number then return the result as a list:
def add_ten(nums):
result = []
for i in nums:
result.append(i+10)
return result
Output:
num_after_add_ten = add_ten([1,20,31,42])
print(num_after_add_ten)>>>>>>>>>>>>>>>>>>>>>
[11,30,41,52]
Change the function from return
to yield
, and use next() to print value one by one:
def add_ten(nums):
for i in nums:
yield (i+10)
Output:
num_after_add_ten = add_ten([1,20,31,42])print(num_after_add_ten)
print next(num_after_add_ten)
print next(num_after_add_ten)
print next(num_after_add_ten)
print next(num_after_add_ten)
print next(num_after_add_ten)>>>>>>>>>>>>>>>>>>>>>
<generator object add_ten at xxxxxx>
11
30
41
52
StopIteration
Note: if the next() function out of range, will raise the StopIteration exception.
Or you can use for loop to print value:
num_after_add_ten = add_ten([1,20,31,42])for num in num_after_add_ten:
print num>>>>>>>>>>>>>>>>>>>>>>>
11
30
41
52
Here is another way to create an operator:
Simply change [ ] to ( ):
#Original
num_after_add_ten = [x+10 for x in [1,20,31,42]]
#Change into Operator type
num_after_add_ten = (x+10 for x in [1,20,31,42])for x in num_after_add_ten:
print x>>>>>>>>>>>>>>>
11
30
41
52
make the operator result as a list by using list():
num_after_add_ten = (x+10 for x in [1,20,31,42])
print list(num_after_add_ten)>>>>>>
[11, 30, 41, 52]
Pros and Cons
Pros
- Generators yield one value at a time from a set of items, not holding all data makes it requires less space of the memory.
- It also took much less time than a list comprehensions when operating
- It is more readable when comparing with using
return
.
Cons
- List comprehensions can be traversed by times while the generator can only be called once.
This tutorial shares very clear and useful examples explaining the benefits and drawbacks:
Python Tutorial: Generators — How to use them and the benefits you receive,
Advantages and disadvantages of generator and list comprehensions in python3
You may also want to know about
Inheritance, Encapsulation and Polymorphism — Object-Oriented Programming in Python
Useful Python tricks you should know before your coding interview
Support my writing by becoming a Medium member today and getting access to an unlimited number of articles.