Python yield and return

Difference between Yield and Return in Python?

In Python, the definition of generators is accomplished with the help of the yield statement. Therefore, before we dive into the specifics of what yield actually does, it’s important that you get an overview of generators. If you have exposure to Python, then there is a good probability that you have previously worked with Python generators. Generators play an important function in Python. In Python, iterators can be generated using generators, however this process takes a somewhat different form.

Python Generators are functions that may be dynamically paused and resumed and create a succession of outcomes. They can also be used to make random numbers. In Python 2.2, generators were introduced for the first time as an elective feature. In Python 2.3, they were made mandatory. The generators functions in Python 2.5 were greatly improved, despite the fact that they already have a sufficient amount of power.

In order to maintain backward compatibility, the addition of generators in Python 2.2 resulted in the introduction of a new keyword called «yield». In order to use generators, we were required to import them from the _future_ module. When generators became the default in Python version 2.3, this was altered to reflect the fact that the change was no longer required.

A function’s execution can be temporarily halted by using the yield statement, which then returns a value to the caller while saving the state of the function for later resumption. This means that the generator as a whole can still be restarted after the return value has been obtained. The execution of the function is terminated with a return statement, which also returns a value to the person who called the function. Your function will not return anything if it is missing.

What is Python Yield?

In Python generators, the yield statement takes the place of a function’s return in order to deliver a value back to the person who called the generator without removing any of the local variables. In order to have a better understanding of the function that the yield statement performs in Python programming, you first need to be familiar with generators.

Читайте также:  Ввести элементы массива питон

The difference between generator functions and normal functions is that generator functions have a «yield» statement in their definitions. This begins with the «yield» keyword, which identifies the generator object that is to be returned to the person who called this function.

In Python, a specific type of function known as a «generator» is one that, rather than returning a data value to the person who called the function, it instead returns another generator object. The execution of the function can be temporarily halted, the state can be saved, and the function can be resumed at a later time, thanks to the yield keyword.

Example

Take a look at the following example −

# Use of yield def printresult(String): for i in String: if i == "p": yield i # Initializing string String = "Happy Birthday" ans = 0 print ("The number of 'p' in word is: ", end = "" ) String = String.strip() for j in printresult(String): ans = ans + 1 print (ans)

Output

The number of 'p' in word is: 2

In contrast to the yield statement, the return statement causes a function to terminate while passing a value back to the function that called it. The functions that are more procedural in nature do not explicitly return anything to their callers and instead return a value that is sent back to the calling function. Even though a function can have several return statements, only one of them can be invoked for each and every one of those statements’ respective invocations.

Almost always, a return statement will be placed at the very end of a function block, and its purpose is to return the ultimate result of carrying out all of the statements that are contained within that function. However, a return statement might also come earlier in the function block to halt the execution of all subsequent statements in that block. This would be the case if it was used to stop the function from being executed. This results in the execution of the program at the caller being restarted instantly. The «None» return object type is the equivalent in Python when no value is supplied for the return object.

Example

The following example shows the use of return in Python −

# Show return statement class Test: def __init__(self): self.str = "Happy Birthday" self.x = "Pradeep" # This function returns an object of Test def fun(): return Test() # Driver code to test above method t = fun() print(t.str) print(t.x)

Output

Difference between Yield and Return in Python

The following table highlights the major differences between Yield and Return in Python −

Читайте также:  Reading standard input python
Basis of comparison Yield Return
Basics In most cases, you will need to use the yield function in order to transform a typical Python function into a generator. In most cases, the conclusion of an execution is signalled by using the return keyword, which «returns» the result to the statement that called it.
Function It takes the place of a function’s return in order to pause the execution of the function without losing any local variables. It exits a function and returns a value to its caller.
Uses When the generator gives an intermediate result to the caller, the caller will use this function. When a function is prepared to convey a value, it is necessary to use this.
Execution The code written after the yield statement is executed in the following function call. While code written after the return statement will not be executed.
Compilation It has the ability to run many times. It only runs once at a time.

Conclusion

The yield statement produces a generator object and can return multiple values to the caller without terminating the program, whereas a return statement is used to return a value to the caller from within a function and it terminates the program. The return statement is used to return the value to the caller from within a function.

Источник

Сравнение операторов yield и return в Python (с примерами)

В этой статье мы расскажем про основные различия между yield и return в Python. А для лучшего понимания этих различий приведем пару примеров.

Встроенное ключевое слово yield используется для создания функций-генераторов. (Про генераторы и их отличия от функций и списков можно подробнее прочитать здесь).

Функция, содержащая yield, может генерировать сразу несколько результатов. Она приостанавливает выполнение программы, отправляет значение результата вызывающей стороне и возобновляет выполнение с последнего yield. Кроме того, функция, содержащая yield, отправляет сгенерированную серию результатов в виде объекта-генератора.

Return также является встроенным ключевым словом в Python. Он завершает функцию, а вызывающей стороне отправляет значение.

Разница между yield и return

Начнем с того, что между yield и return есть много заметных различий. Для начала давайте обсудим их.

return yield
Оператор return возвращает только одно значение. Оператор yield может возвращать серию результатов в виде объекта-генератора.
Return выходит из функции, а в случае цикла он закрывает цикл. Это последний оператор, который нужно разместить внутри функции. Не уничтожает локальные переменные функции. Выполнение программы приостанавливается, значение отправляется вызывающей стороне, после чего выполнение программы продолжается с последнего оператора yield.
Логически, функция должна иметь только один return. Внутри функции может быть более одного оператора yield.
Оператор return может выполняться только один раз. Оператор yield может выполняться несколько раз.
Return помещается внутри обычной функции Python. Оператор yield преобразует обычную функцию в функцию-генератор.
Читайте также:  Php http request with header

Пример 1

Теперь давайте рассмотрим разницу между операторами return и yield на примерах.

В приведенном ниже коде мы использовали несколько операторов возврата. Вы можете заметить, что выполнение программы прекратится уже после первого оператора return. Весь код, идущий после, не будет выполнен.

num1 =10 num2=20 def mathOP(): return num1+num2 return num1-num2 return num1*num2 return num1/num2 print(mathOP())

В выводе видно, что функция возвращает только первое значение, после чего программа завершается.

snimok

Чтобы выполнить аналогичную задачу с несколькими операторами return, нам нужно создать четыре разные функции для каждого типа арифметической операции.

num1 =10 num2=20 def sumOP(): return num1+num2 def subtractOP(): return num1-num2 def multiplicationOP(): return num1*num2 def divisionOP(): return num1/num2 print("The sum value is: ",sumOP()) print("The difference value is: ",subtractOP()) print("The multiplication value is: ",multiplicationOP()) print("The division value is: ",divisionOP())

Запустив данный код, получим следующий результат:

snimok1

Однако мы можем выполнить эти арифметические операции внутри одной функции-генератора, используя несколько операторов yield.

num1 =10 num2=20 def mathOP(): yield num1+num2 yield num1-num2 yield num1*num2 yield num1/num2 print("Printing the values:") for i in mathOP(): print(i)

snimok2

Пример 2

Давайте рассмотрим еще один пример использования операторов return и yield.

Создадим список чисел и передадим его в функцию mod() в качестве аргумента. Далее, внутри функции, мы проверяем каждый элемент списка. Если он делится без остатка на 10, то мы его выводим.

Для начала давайте реализуем этот пример в нашем скрипте Python с использованием оператора return.

myList=[10,20,25,30,35,40,50] def mod(myList): for i in myList: if(i%10==0): return i print(mod(myList))

Оператор return возвращает только первое число, кратное 10, и завершает выполнение функции.

snimok3

Теперь давайте реализуем тот же пример, используя оператор yield.

myList=[10,20,25,30,35,40,50] def mod(myList): for i in myList: if(i%10==0): yield i for i in mod(myList): print(i)

Получим следующий результат:

snimok4

Заключение

В этой статье мы провели сравнение yield и return в Python, перечислили все заметные различия между ними и разобрали это на примерах.

И return, и yield являются встроенными ключевыми словами (или операторами) Python. Оператор return используется для возврата значения из функции. При этом он прекращает выполнение программы. А оператор yield создает объект-генератор и может возвращать несколько значений, не прерывая выполнение программы.

Источник

Оцените статью