Python what does yield returns?

Geomario
2 min readOct 13, 2020

Working with iterables leads you inevitably to Python's question, What does the “yield” keyword do in Python?

What does yield returns?

I am an assistant researcher at the E.ON Energy Research centre from the RWTH in Germany, and I have lost several battles when exploring and analysing data during iteration.

To clarify the keyword “yield” job, we should first understand what its an iteration. An Iteration its simply the value extraction from an iterable object, in short, returning the value one at a time.

#List
autos = ["BMW", "VW", "Ford"] ...(1)
for auto in autos:
print (auto) ...(2)
>>> "BMW".
"VW"
"Ford"

In the example, the iteration will return the auto value from the list (1), one by one (2). Therefore, we can use the auto value any time in our code. What happens when we need the auto value just once? We create a generator!

#Generator
autos = ("BMW", "VW", "Ford") ... (1)
for auto in autos: ... (2)
print (auto)
>>> "BMW" ... (3)
"VW"
"Ford"

In the example, we created a generator. Seems the same? have a look in the square brackets from the list (1). In this case, we create a generator with the parenthesis. As a result, computer memory will not be compromised. Simultaneously, the generator reads the “for in” instructions and returns the value; it forgets the value and prints the next one (2). In the example, after it prints the string “BMW”, it forgets it and prints the string “VW” subsequently (3). Hence, we can use the value just once.

If you ask yourself why we need this, it is because when working as a Data Scientist or managing several amounts of Data as a researcher, you are interested in just a value once and save computer memory, for instance.

How generators, yield and iterables are connected? Generators are returned in functions with the keyword “yield” in Python programming language. The yield keyword in python works as a return in a function, and it will return a generator when invoque in it.

def function_yield():
autos = ("BMW", "VW", "Ford")
for auto in autos:
yield auto ... (1)

In the example, the function will return a generator (1). The data values will be available just once in your code. After the function executes in your code, your code continues from where it started the function.

I was hoping you could have a look in my Youtube video tutorial about yield ⬇️

Python what does yield returns? FreeDataScientist Youtube Channel

Yield in Python its a must to master it while it would lead to discoveries in the keyword's execution. We can talk about them in the next posts.

Thanks & Happy coding!

PS. Would not hurt you if you have a look in my video and give me a clap 👏! Follow me!

--

--

Geomario

👨‍💻 Software & Data Developer | Software Research Engineer | MLE