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...

Keyboard Shortcuts

Navigation
Next / previous item
j/k
Open post
oorEnter
Preview post
v
Post Actions
Love post
a
Like post
l
Dislike post
d
Undo reaction
u
Recommendations
Add interest / feed
Enter
Not interested
x
Go to
Home
gh
Interests
gi
Feeds
gf
Likes
gl
History
gy
Changelog
gc
Settings
gs
Browse
gb
Search
/
General
Show this help
?
Submit feedback
!
Close modal / unfocus
Esc

Press ? anytime to show this help