5 ms·
Well, 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/bui
by Vendan 8y ago
Well, 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.