Mastering Python Generators and yield: Efficient Iteration Explained
Mastering Python Generators and yield: Efficient Iteration Explained ⚙️
Generators in Python offer a way to handle large or infinite data streams efficiently by yielding items one at a time, saving memory and improving performance.
✅ Basic Generator Usage
Using yield allows a function to return values one by one while remembering its state.
# Basic generator example
def simple_gen():
yield 1
yield 2
yield 3
gen = simple_gen()
print(next(gen)) # 1
print(next(gen)) # 2
print(next(gen)) # 3
✅ Creating an Infinite Counter
Generators can be used to produce an infinite sequence without consuming much memory.
# Infinite counter generator
def infinite_counter(start=0):
while True:
yield start
start += 1
counter = infinite_counter()
for _ in range(5):
print(next(counter))
✅ Filtering with Generators
You can use generators to filter data based on conditions without creating intermediate lists.
# Filtering even numbers with a generator
def even_numbers(nums):
for num in nums:
if num % 2 == 0:
yield num
numbers = [1, 2, 3, 4, 5, 6]
evens = even_numbers(numbers)
print(list(evens)) # [2, 4, 6]
Learning how to create and use generators makes your Python programs more efficient and professional, especially when dealing with large datasets or continuous data streams!
Real efficiency comes from smart iteration. Master generators, and make your Python code more powerful and elegant! ๐
Icons by Flaticon
Comments
Post a Comment