[Python-ideas] Make len() usable on a generator
Stephen J. Turnbull
stephen at xemacs.org
Fri Oct 3 17:43:50 CEST 2014
Thomas Chaumeny writes:
> Yes, it has to exhaust the generator to find the length, but that also is
> what list(generator) or sum(generator) have to do and yet they are allowed
> constructions.
sum(1 for x in generator)
I'm on the fence about whether I prefer that to len(generator), on the
grounds that I normally would not expect len to use up the sequence,
while I sort of expect sum to do so (for values of "sort of expect"
that acknowledge that
s = [1, 2, 3]
print(sum(s))
doesn't "use up" s in fact, but it does "use" all the values).
More information about the Python-ideas
mailing list