|
| 1 | +--- |
| 2 | +Title: 'yield' |
| 3 | +Description: 'Turns a function into a generator, producing values one at a time while retaining state between calls.' |
| 4 | +Subjects: |
| 5 | + - 'Code Foundations' |
| 6 | + - 'Computer Science' |
| 7 | +Tags: |
| 8 | + - 'Functions' |
| 9 | + - 'Iterators' |
| 10 | + - 'Python' |
| 11 | +CatalogContent: |
| 12 | + - 'learn-python-3' |
| 13 | + - 'paths/computer-science' |
| 14 | +--- |
| 15 | + |
| 16 | +The **`yield`** keyword is used in a [function](https://www.codecademy.com/resources/docs/python/functions) to make it a [generator function](https://www.codecademy.com/resources/docs/python/generators). Generator functions return an [iterator](https://www.codecademy.com/resources/docs/python/iterators) that produces one value per call instead of all values at once. To get a value from a generator, call the `next()` function on it. The code within the function is executed up to the `yield` statement. When `yield` is encountered, the current value is returned. The function maintains its state between calls, resuming from where it left off. This enhances memory efficiency for large datasets and allows better resource management, such as processing streams or database results. |
| 17 | + |
| 18 | +## Syntax |
| 19 | + |
| 20 | +```pseudo |
| 21 | +def generatorFunction(): |
| 22 | + # ... |
| 23 | + yield value |
| 24 | + # ... |
| 25 | +``` |
| 26 | + |
| 27 | +**Parameters:** |
| 28 | + |
| 29 | +- `value`: The object to be produced by the generator. If omitted, `None` is yielded. |
| 30 | + |
| 31 | +**Return value:** |
| 32 | + |
| 33 | +`yield` returns the next value in a generator sequence to the caller. |
| 34 | + |
| 35 | +## Example |
| 36 | + |
| 37 | +In this example, the generator yields numbers from 1 to 5, producing values one at a time: |
| 38 | + |
| 39 | +```py |
| 40 | +# Define a generator function that yields numbers from 1 to 5 |
| 41 | +def count_up_to_five(): |
| 42 | + for i in range(1, 6): |
| 43 | + yield i |
| 44 | + |
| 45 | +# Create the generator |
| 46 | +gen = count_up_to_five() |
| 47 | + |
| 48 | +# Iterate over the generator to get values |
| 49 | +for number in gen: |
| 50 | + print(number) |
| 51 | +``` |
| 52 | + |
| 53 | +The output of this code is: |
| 54 | + |
| 55 | +```shell |
| 56 | +1 |
| 57 | +2 |
| 58 | +3 |
| 59 | +4 |
| 60 | +5 |
| 61 | +``` |
| 62 | + |
| 63 | +> **Note:** `for` loop implicitly calls `next()` method on the generator `gen`. |
| 64 | +
|
| 65 | +In this code: |
| 66 | + |
| 67 | +- `count_up_to_five` is defined as a generator function. |
| 68 | +- `count_up_to_five()` is called and it returns a generator object without executing the function body. |
| 69 | +- `for` loop calls `next()` on `gen`, which starts executing `count_up_to_five`. |
| 70 | +- `count_up_to_five` runs until it hits the `yield` statement, returning the current value of `i`. |
| 71 | +- `for` loop calls `next()` again, `count_up_to_five` function resumes right after the `yield` statement. |
| 72 | + |
| 73 | +## Codebyte Example: Printing a list of words with `return` vs. `yield` |
| 74 | + |
| 75 | +This Codebyte example shows the difference between using `return` and `yield` in a function: |
| 76 | + |
| 77 | +```codebyte/python |
| 78 | +from typing import List |
| 79 | +
|
| 80 | +# A list of words to print |
| 81 | +words: List[str] = ["Hello", "yield", "!"] |
| 82 | +
|
| 83 | +# Function using return |
| 84 | +def print_list_by_return(element: str): |
| 85 | + print("Before return") |
| 86 | + return element |
| 87 | + print("After return") # never executes |
| 88 | +
|
| 89 | +# Function using yield |
| 90 | +def print_list_by_yield(element: str): |
| 91 | + print("Before yield") |
| 92 | + yield element |
| 93 | + print("After yield") # executes when generator resumes |
| 94 | +
|
| 95 | +# Calling functions |
| 96 | +print("calling print_list_by_return:\n") |
| 97 | +for word in words: |
| 98 | + print(print_list_by_return(word)) |
| 99 | +
|
| 100 | +print(f"\n{'#'*20}\n") |
| 101 | +
|
| 102 | +print("calling print_list_by_yield:\n") |
| 103 | +for word in words: |
| 104 | + yield_obj = print_list_by_yield(word) |
| 105 | + for value in yield_obj: |
| 106 | + print(value) |
| 107 | +``` |
| 108 | + |
| 109 | +> **Note:** Because `yield` produces an iterator, we need to loop through the iterator to get the values to print. If not, we'll see the generator object memory address printed. |
| 110 | +
|
| 111 | +In this code: |
| 112 | + |
| 113 | +- The `print_list_by_return` function prints only `"Before return"` because it exits immediately. |
| 114 | +- The `print_list_by_yield` function prints `"Before yield"` and `"After yield"` for each item, pausing at `yield` and resuming when iterated. |
0 commit comments