Python

Python – What is yield for? when to use it?

January 8, 2022

Python – What is yield for? when to use it?

In this article, we’ll learn what is yield for, which basically creates a generator, that is, a list of data that is consumed on demand.

what is yield for cover

Hey you programmer, okay? Let’s learn more about Python!

Before understanding what yield is, there are two concepts you need to understand.

They are: iterations and generators

The iterations 

You can use a structure like this to iterate through each item in a list.

This is called an iteration, see an example:

list = ['hora','de','codar']

for item in list:
 print(item)

Which will return the following:

hora
de
codar

terations are good because you can iterate through a list, however large it is, and execute different logic based on each value presented or entered into it.

The generators

Generators are basically values generated by iterations, which are not saved in memory.

The generator will calculate each of the iteration values and we can use this value as we want too

See an example:

generator = (x+10 for x in range(5))

for item in generator:
 print('x + 10: ' + str(item))

And after this execution, the generator can no longer be used, this is a peculiarity of this instruction

And the yield?

Yield is basically a keyword that is used similar to return

But this function returns a generator!

See the example:

def usingYield(x):
 for i in range(x):
  if(i % 2 == 0):
   yield 'even'
  else:
   yield 'odd'

newgenerator = usingYield(10)

for i in newgenerator :
print(i)

This function will generate a generator with odd or even, depending on the iteration number, and the length of the list also depends on the parameter passed

But the central idea here is the yield generating a generator

So here we have the following output:

even
odd
even
odd
even
odd
even
odd
even
odd

And when should  we use generators?

When we have, for example, very large lists and we don’t want to have that list allocated in our memory

So we started with the generators strategy to save resources that can be done with the first way taught running on loop or yield basis

Conclusion

In this article we learned  what yield is for and also an example of when should we use it

Basically, yield creates a generator based on what it would return from a function.

We should use the yield or the generator when there is a very large list we want to handle, so we don’t have to save this one in memory

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x