Yield vs return
Return
return
keyword implies the output of a function. It stops the function after
running.
src.intermediate.yield_vs_return.return_even_numbers(n)
Return even numbers until n (inclusive).
Returns:
Name | Type | Description |
---|---|---|
even_numbers |
list[int]
|
List of even numbers until n (inclusive). |
Source code in src/intermediate/yield_vs_return/yield_vs_return.py
10 11 12 13 14 15 16 17 18 19 20 |
|
Yield
yield
keyword also returns a value, but a function can yield multiple outputs,
so it does not stop the entire function. Yield returns a generator object, which
is an iterator. It can be used in loops.
src.intermediate.yield_vs_return.yield_even_numbers(n)
Yield even numbers until n (inclusive).
Returns:
Name | Type | Description |
---|---|---|
even_numbers |
Generator
|
List of even numbers until n (inclusive). |
Source code in src/intermediate/yield_vs_return/yield_vs_return.py
23 24 25 26 27 28 29 30 31 |
|
You can use yield instead of return when the data size is large, as it doesn't store in memory the entire result, only when function is called. It is an efficient way of producing data that is big or infinite.
src.intermediate.yield_vs_return.yield_fibonacci_numbers()
Yield Fibonacci series.
Returns:
Name | Type | Description |
---|---|---|
fibonacci_numbers |
Generator
|
List of numbers of the Fibonacci series. |
Source code in src/intermediate/yield_vs_return/yield_vs_return.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
|