4 ms·
That's not intuitive at all. That's equivalent to: if len(items) == 0: print(y) else: for item in items: print(item) Which
by cup-of-tea 8y ago
That's not intuitive at all. That's equivalent to:
if len(items) == 0:
print(y)
else:
for item in items:
print(item)
Which means there's a whole extra implicit if. The for in Python is really this:
it = iter(items)
while True:
try:
item = next(it)
except StopIteration:
print("else")
break
print(item)
Where that try/except is like "if there is a next item do this, else do this", hence:
for item in items:
print(item)
else:
print("else")
- Vendan 8y agoNever said intuitive, but that construct is EXTREMELY useful for things like "no results found" and such, when a list of items is empty. Therefore, it is usually explained quite early and used often in template languages that have it. This is the first time I've seen python's, after dealing with several large codebases written in python.