5 ms·
I know nothing about APL. But I think I would write it the same way as the OP. I also think use len is better to convey counting operation: len(age for age in
by aynyc 3y ago
I know nothing about APL. But I think I would write it the same way as the OP. I also think use len is better to convey counting operation:
len(age for age in ages if age > 17)
- deleted 3y ago[deleted]
- vore 3y agoI don’t think you can do that with a generator expression. You would have to write: sum(1 for age in ages if age > 17)
- Nihilartikel 3y agoIt would eat ram at scale but you could wrap the gen expression with [] for a list comprehension and that would work.
- deleted 3y ago[deleted]
- deleted 3y ago[deleted]
- aynyc 3y agoah, yes, of course, forgot the generator.
- nomel 3y agoIf you're going to go that route, I think this makes more sense: count_over_17 = [age > 17 for age in ages].count(True)
- dragonwriter 3y agoFor a very large sequence traversing it to build a list and then traversing the list to do something you could do in one traversal without creating a list may be undesirable.
- nomel 3y agoIn a very large sequence, you would be using numpy. I assumed the purpose of their example was some sort of clarity, over `sum(age > 17 for age in ages)`, rather than performance.
- dragonwriter 3y agoYou can't call len on a gen exp, though you could define a count function. For an unsafe variant: def count(it): return sum(1 for _ in it) Which is basically just putting a friendly name on the approach from the article. For a safe version, you probably want to wrap it in another generator that bails with an exception at a specified size so you don’t risk an infinite loop. def safe_count(it, limit=100): # returns None if actual length > limit nit = zip(range(limit+1), it) if (l := sum(1 for _ in nit)) <= limit: return l Of course, you can just convert to a list and return the length, but sometimes you don’t want to build a list in memory.