About 1618 letters

About 8 minutes

#Generators in Python

A generator in Python is a special type of iterator that produces values one at a time using a certain formula, instead of storing multiple values like a list. This allows for better memory efficiency.

#Generator Function

A generator function uses the yield statement instead of return to return values. When the function is called, it doesn’t execute immediately, but instead returns a generator object.

Each time the generator is iterated, the function runs until it hits a yield statement, at which point it returns a value. On the next iteration, execution resumes just after the yield statement, not from the beginning of the function.

Example:

# Generator function def count_up_to(max): count = 1 # Initialize starting at 1 while count <= max: yield count # Returns count each time next() is called count += 1 # Create generator object counter = count_up_to(10) # Using the generator print(next(counter)) # Output: 1 print(next(counter)) # Output: 2 print(next(counter)) # Output: 3 for value in counter: print(value) # Output remaining values

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

#Generator Expression

Similar to container comprehensions, generators can also be created using generator expressions. A generator expression is a looping expression enclosed in parentheses () that yields values one at a time.

# Generator expression numbers: tuple[int] = (x**2 for x in range(10)) print(numbers) for value in numbers: print(value)

>>> Establishing WebAssembly Runtime.

>>> Standby.

Powered by Shift.

Created in 5/23/2025

Updated in 5/23/2025