The Secret Life of Python: The Iterator Protocol - Why For Loops Are Magic
dev.to·5h·
Discuss: DEV
Flag this post

Timothy was explaining Python to a colleague from C++ when he got stumped. “So in Python, you can loop over lists, dictionaries, files, strings, ranges, sets... how does for know what to do with all these different types?”

Margaret overheard and smiled. “That’s the iterator protocol - one of Python’s most elegant designs. Every type that works with for speaks the same language, and you can teach your own objects that language too. Let me show you the magic.”

The Puzzle: For Loops Work on Everything

Timothy showed Margaret what confused him:

def demonstrate_for_loop_versatility():
"""For loops work on so many different types!"""

# Loop over a list
for item in [1, 2, 3]:
print(item, end=' ')
print("← list")

# Loop over a string
for char in "hello":
print(char, end...

Similar Posts

Loading similar posts...