What does the "yield" keyword do in Python?

Free Coding Questions Catalog
Boost your coding skills with our essential coding questions catalog. Take a step towards a better tech career now!

What Does the "yield" Keyword Do in Python?

The yield keyword in Python is used to create a generator, which is a special type of iterable that generates values one at a time and maintains its state between each generation. Unlike a regular function that returns a single value and terminates, a generator function with yield can produce a series of values over time, allowing you to iterate over them using a loop or other iteration tools.

How yield Works

When the yield keyword is encountered, the state of the function is saved, and the yielded value is returned to the caller. The next time the generator's __next__() method is called, the function resumes execution immediately after the yield statement, preserving the state (local variables, instruction pointer, etc.) from the previous execution.

Basic Example

Here’s a simple example to demonstrate how yield works:

def simple_generator(): yield 1 yield 2 yield 3 # Using the generator gen = simple_generator() for value in gen: print(value)

Output:

1
2
3

Advantages of Using yield

  1. Memory Efficiency:

    • Generators are memory efficient because they generate items one at a time, only when needed, rather than storing the entire sequence in memory.
  2. Lazy Evaluation:

    • Values are computed on-the-fly and are not stored in memory, which can be beneficial for large datasets or infinite sequences.
  3. State Retention:

    • Generators automatically retain their state between each yield, making it easier to manage complex iteration logic without the need for explicit state management.

Example: Fibonacci Sequence

A common use case for generators is generating sequences, such as the Fibonacci sequence:

def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b # Using the generator fib_gen = fibonacci() for _ in range(10): print(next(fib_gen))

Output:

0
1
1
2
3
5
8
13
21
34

Example: Reading Large Files

Using yield to read a large file line-by-line can be more memory efficient than reading the entire file at once:

def read_large_file(file_path): with open(file_path, 'r') as file: for line in file: yield line # Using the generator for line in read_large_file('large_file.txt'): print(line.strip())

Generators vs. Regular Functions

Regular Function:

  • Returns a single value.
  • Terminates execution after returning the value.

Generator Function:

  • Uses yield to produce a series of values.
  • Can yield multiple times, resuming execution where it left off each time.

Summary

The yield keyword in Python is a powerful tool for creating generators, which are iterators that generate values one at a time, on-the-fly, in a memory-efficient manner. By using yield, you can handle large datasets or sequences without loading them entirely into memory, and you can create complex iteration logic without explicitly managing state.

For more in-depth knowledge and practical examples of advanced Python concepts, consider exploring courses like Grokking the Coding Interview on DesignGurus.io. This course provides comprehensive coverage of essential coding and algorithm techniques, helping you master Python and other programming skills needed for technical interviews.

TAGS
System Design Interview
CONTRIBUTOR
Design Gurus Team

GET YOUR FREE

Coding Questions Catalog

Design Gurus Newsletter - Latest from our Blog
Boost your coding skills with our essential coding questions catalog.
Take a step towards a better tech career now!
Explore Answers
Why Apple interview answer?
Which programming language is used for mobile development?
What is a group anagram?
Learn how to identify and group anagrams with this concise guide.
Related Courses
Image
Grokking the Coding Interview: Patterns for Coding Questions
Image
Grokking Data Structures & Algorithms for Coding Interviews
Image
Grokking Advanced Coding Patterns for Interviews
Image
One-Stop Portal For Tech Interviews.
Copyright © 2024 Designgurus, Inc. All rights reserved.