3 ms·
Yeah I get that it can be useful, but I just don't like ending a loop in two different ways. It just seems too easy to end up writing something like: for x
by contravariant 8y ago
Yeah I get that it can be useful, but I just don't like ending a loop in two different ways. It just seems too easy to end up writing something like:
for x in sorted_list:
if x == to_find:
print("found")
break # we've found a match
elif to_find > x:
break # match is not possible
else:
print("not found)
- gridspy 8y ago") # There you go Also, nice counterexample.
- fyi1183 8y agoFunny, I actually like for-else because it can simplify loop exits. First of all, the core of a linear search loop always has two exits: the break and the normal (unsuccessful) loop exit. But in a lookup-or-insert pattern, a regular for loop has two possible states that the system can be in at the end of the loop. With a for-else loop, you can put the or-insert part into the else block, so that there is a simpler invariant: after the loop construct, the element always exists and has been found. I was honestly surprised by all the negativity in this thread. To offer an alternative opinion, there have been plenty of times when I missed having for-else while writing C.
- gvx 8y agoI feel the same way. For-else is one of those things that make me miss Python when I'm working in another language, alongside things like list/set/dict comprehensions, Python's object model and it's way of dealing with generators and iteration.