Table of Contents
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:
“`pythondef my_iterator(): # Yield a sequence of numbers for i in range(10): yield i
iterator = my_iterator()
for number in iterator: print(number)“`
“`pythondef my_generator(): # Yield a sequence of squares for number in range(10): yield number ** 2
generator = my_generator()
for square in generator: print(square)“`
Benefits:
Examples:
“`python
def count_to(n): for i in range(n): yield i
for num in count_to(5): print(num) # Output: 0, 1, 2, 3, 4
def multiples(x): for i in range(x): yield i * x
for multiple in multiples(3): print(multiple) # Output: 0, 3, 6, 9“`
Additional Notes:
Table of Contents
Categories