2 mins read

Yield

Definition:

yield is a keyword in Python that is used to suspend the execution of a function and allow other code to run. It is commonly used in iterators and generators to provide a way to iterate over a sequence of data without creating a list or tuple.

Usage:

  • Iterator methods:

“`pythondef my_iterator(): # Yield a sequence of numbers for i in range(10): yield i

Create an iterator

iterator = my_iterator()

Iterate over the iterator

for number in iterator: print(number)“`

  • Generators:

“`pythondef my_generator(): # Yield a sequence of squares for number in range(10): yield number ** 2

Create a generator

generator = my_generator()

Iterate over the generator

for square in generator: print(square)“`

Benefits:

  • Lazy evaluation: Yielding allows for lazy evaluation, which means that the generator only creates the data as needed, reducing memory usage.
  • Iterability: Yielding makes it easier to create iterators and generators, which are essential for iterative programming.
  • Conciseness: Yielding simplifies code by reducing the need for intermediate data structures.
  • Efficiency: Yielding can be more efficient than creating a list or tuple, as it reduces the overhead of object creation.

Examples:

“`python

Function with a yield statement

def count_to(n): for i in range(n): yield i

Use the function as an iterator

for num in count_to(5): print(num) # Output: 0, 1, 2, 3, 4

Generator function

def multiples(x): for i in range(x): yield i * x

Use the generator function

for multiple in multiples(3): print(multiple) # Output: 0, 3, 6, 9“`

Additional Notes:

  • Yielding is a cooperative operation, meaning that the function must explicitly yield control to the interpreter.
  • Yielding can be used in both synchronous and asynchronous contexts.
  • It is a key concept in Python’s support for functional programming.

Disclaimer