Python Generators

In Python, a generator is a special type of function that allows you to iterate over a sequence of values, without actually constructing the entire sequence in memory at once. Instead, the generator produces one value at a time, and remembers where it left off, so that it can resume iteration later on. This can be useful when working with very large datasets, or when you want to conserve memory.

  • Generators are defined with the def keyword.
  • It uses the yield keyword.
  • It can use several yield keyword.
  • It returns an iterator.

Here’s an example of a simple generator function in Python:

def my_generator():
    yield 1
    yield 2
    yield 3

In this example, the yield keyword is used instead of the return keyword. When this function is called, it will not execute immediately. Instead, it will return a generator object, which can be used to iterate over the values in the sequence:

gen = my_generator()
print(next(gen))  # Output: 1
print(next(gen))  # Output: 2
print(next(gen))  # Output: 3

When the next() function is called on the generator object, the function will execute up to the next yield statement, and then pause, returning the yielded value. The next time next() is called, the function will resume execution, and continue where it left off.

Generators can also be used with loops:

for value in my_generator():

In this example, the for loop will automatically call next() on the generator object until there are no more values to yield.

Generator functions can be very powerful, and are often used in conjunction with other Python features like list comprehensions and built-in functions like filter() and map().

Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial