3 ms·
For-else is nothing. The really weird one is the Try-else. The For/While-else does exactly what I expect. I'm not sure why others find it confusing. The Try-e
by cup-of-tea 8y ago
For-else is nothing. The really weird one is the Try-else.
The For/While-else does exactly what I expect. I'm not sure why others find it confusing.
The Try-else does make some code more readable but is quite rare I would say.
- Vendan 8y agoWell, for one thing, a few templating engines have a "for each item, print x, else if there are no items, print y". (for instance: https://handlebarsjs.com/builtin_helpers.html#iteration https://handlebarsjs.com/builtin_helpers.html#iteration)
- cup-of-tea 8y agoThat'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.