Coder Life
Published in

Coder Life

Yield — Generators in Python

Photo by Eduardo Cano Photo Co. on Unsplash

Let’s see how it works by code

def add_ten(nums):
result = []
for i in nums:
result.append(i+10)
return result
num_after_add_ten = add_ten([1,20,31,42])
print(num_after_add_ten)
>>>>>>>>>>>>>>>>>>>>>
[11,30,41,52]
def add_ten(nums):
for i in nums:
yield (i+10)
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
num_after_add_ten = add_ten([1,20,31,42])for num in num_after_add_ten:
print num
>>>>>>>>>>>>>>>>>>>>>>>
11
30
41
52
#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
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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store