Date:

Share:

Python Yield vs Return

Related Articles

introduction

God function Is a powerful tool used in many programming languages. In Python, h return A statement is used to tell a function to issue a specific value to the caller. However, there is another lesser known saying by name yield Can be used to achieve different behavior.

In this article, we will discuss the differences between returns in Python. In order to do this, we will explore other concepts including iterators and generators.

What is the Return A statement in Python?

Functions are an essential part of Python that allow blocks of code to be reused multiple times. Functions can also make use of arguments to make them dynamic so that we can call the same function but change specific values ​​resulting in a different output or flow of instructions.

By using return A statement in a function We can specify the output of the function and finish reading the function. for example:

>>> def func(x, y):
...     result = x + y
...     return result
... 
>>> 

This example shows a function that takes two variables and returns their sum. A return statement is used to set the output of the function to be the variable named result, Which is the sum of x and y. We can then call the function with different variables:

>>> print(func(1, 2))
3
>>> print(func(3, 4))
7

For more information on function calls, see “What is a function call?” Section in our post Python SyntaxError: Can’t Assign to Function Call.

But what happens if we do not include a return statement within a function? A return statement is not actually required to define a valid function. In fact, there are many times when you do not even need it. for example:

>>> def func(x, y):
...     result = x + y
... 
>>> print(func(1, 2))
None

If we omit the return statement as seen in the previous example, the function returns a default value of None.

As another example, suppose the only thing we want to achieve is to print the result variable. We can just do it inside the function and then we will not need the return statement:

>>> def func(x, y):
...     result = x + y
...     print(result)
... 
>>> func(1, 2)
3

What is an iterator in Python?

English iteration means a repetition of a process that reflects the use of iterables in Python. A Can be repeated Is a structured object that can be passed through one element at a time. For example, strings, lists and tuples are repeatable because you can go through any element in them one by one in order.

A Iterator Python is an object that can be applied to __next__() Method and returns through it. We can turn an iterator as a list into an iterator with the iter() Built-in function.

>>> a = [1, 2, 3, 4]
>>> iter_a = iter(a)
>>> iter_a
<list_iterator object at 0x7fac2b1d5910>
>>> type(iter_a)
<class 'list_iterator'>
>>> iter_a.__next__()
1
>>> iter_a.__next__()
2
>>> next(iter_a)
3
>>> next(iter_a)
4
>>> next(iter_a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> 

In the example above, we used iter() Function to make the list an iterator stored in a variable iter_a. We can also use __iter__() Method to do the same. So we can use __next__() The method or the next() Function Repeat the list. As soon as we reach the end of the list we will get a StopIteration Outstanding. As you can guess, this shows that we can go through an iterator only once.

We can also run an iterator through a for loop:

>>> iter_a = iter(a)
>>> for num in iter_a:
...     print(num)
... 
1
2
3
4

For Loops connect naturally with iterators because they are designed to do just that – read on __next__() Iterator method to provide the next value for using a loop.

What are Python Generators?

In Python, a generator Is a particular type of iterator. A generator is an iterator, but an iterator is not a generator. A generator is a type of function that returns an iterator instead of a specific value. This means that the resulting output of the function can be called several times using next() To yield different values ​​continuously.

A common form of generator in Python is “one line for loops”. for example:

>>> b = (n+1 for n in a)
>>> b
<generator object <genexpr> at 0x7fac2b16b580>
>>> next(b)
2
>>> next(b)
3

Here, we create a generator object, with “one row per loop” inside parentheses. And since the generators are iterators, we can perform an iteration through them with the next function.

As we will see now, we can also create a generator with a normal function definition by using yield Disclaimer.

What is Python Yield?

God yield A statement in Python is especially used within function definitions for generating generators. for example:

>>> def g():
...     yield 1
...     yield 2
...     yield 3
... 
>>> 
>>> a = g()
>>> type(a)
<class 'generator'>
>>> next(a)
1
>>> next(a)
2
>>> next(a)
3
>>> next(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

Here, we define a function g With three return statements. In this example, we learn that we can actually use the return theorem multiple times in a function. The function call is now the type generator. When we return through the generator with next (), each value is generated in sequence.

Another way to use yield is shown below:

>>> def g2(ls):
...     for i in ls:
...             yield i + 1
... 
>>> 
>>> a = [1, 2, 3, 4]
>>> 
>>> b = g2(a)
>>> next(b)
2
>>> next(b)
3
>>> next(b)
4
>>> next(b)
5

Here, we produce the same generator we did in the previous section with “one line per loop”. Then we go through the generator with the following.

What is the difference between return and return?

Both return statements and return are used within function definitions. However, a return statement is made only once in a call to a single function, but the return can be used as we saw in the previous section several times in a call to a single function. Furthermore, the return statement returns a variable or specific expression value, while the return statement returns an iterator that can be iterated using next().

The return statement is also more effective in memory than the return statement in some situations. for example:

>>> ls = [1, 2, 3, 4]
>>> 
>>> def func(ls):
...     new_ls = []
...     for i in ls:
...             new_ls.append(i + 1)
...     return new_ls
... 
>>> 
>>> for i in func(ls):
...     print(i)
... 
2
3
4
5

Here, we want to change the list ls And then loop through it without changing the original list.

Upon return, we must create a new list, modify the list, and then return the new list. When moving through a loop in the new list, this list will be stored in memory. We will now look at the approach with the return statement.

>>> ls = [1, 2, 3, 4]
>>>
>>> def func(ls):
...     for i in ls:
...             yield i + 1
... 
>>> for i in func(ls):
...     print(i)
... 
2
3
4
5

We can see that the generator will yield each item in the list with 1 added to it. Now, when we run the for loop on the function, it simply returns the following result from the iterator each time. We no longer need to store another list in memory. This makes the yield more efficient in memory in this case.

Summary

In this article, we have compared the return and return keywords in Python and figured out when it might be right to use one over the other. We first briefly researched what the functions and return statements are in Python. Then we realized what iterals and generators are. We then saw how using yield within a function turns that function into a generator. Finally, we linked all of these concepts together to understand the difference between return and return.

Next steps

If you are interested in learning more about the basics of Python, coding and software development, please refer to the basics of coding for developers, where we cover the essential languages, concepts and tools you will need to become a professional developer.

Thanks and happy coding! We hope you enjoyed this article. If you have any questions or comments, please feel free to contact jacob@initialcommit.io.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Popular Articles