6 ms·
You 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 basi
by dragonwriter 3y ago
You 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.