0
0
PythonConceptBeginner · 3 min read

What is yield in Python: Explanation and Examples

yield in Python is a keyword used inside a function to make it a generator. It pauses the function, returns a value, and resumes later, allowing efficient iteration over large data without storing everything in memory.
⚙️

How It Works

Imagine you are reading a book but only want to read one page at a time instead of the whole book at once. yield works like a bookmark that saves your place in the function. When the function reaches yield, it sends back a value and pauses, waiting for you to ask for the next one.

This means the function does not run all at once but step-by-step, producing values one by one. This is very useful when dealing with large data or streams because it saves memory and time by not creating a full list upfront.

💻

Example

This example shows a simple generator function that yields numbers from 1 to 3 one at a time.

python
def count_up_to_three():
    yield 1
    yield 2
    yield 3

for number in count_up_to_three():
    print(number)
Output
1 2 3
🎯

When to Use

Use yield when you want to handle large data or streams without loading everything into memory. For example, reading large files line by line, generating infinite sequences, or processing data lazily.

This helps keep your program fast and memory-efficient, especially when working with big data or slow data sources.

Key Points

  • yield turns a function into a generator that produces values one at a time.
  • It pauses the function, saving its state, and resumes when the next value is requested.
  • Generators are memory-efficient for large or infinite data.
  • You can iterate over generators with loops like for.

Key Takeaways

yield creates generators that produce values lazily, saving memory.
Generators pause and resume, allowing step-by-step data processing.
Use yield for large data, streams, or infinite sequences.
You can loop over generators just like lists but without storing all data.