[Python-ideas] Make len() usable on a generator

Nick Coghlan ncoghlan at gmail.com
Fri Oct 3 17:32:59 CEST 2014


On 4 October 2014 01:21, Thomas Chaumeny <t.chaumeny at gmail.com> wrote:
> 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.

It's appropriate to look at the big-O algorithmic complexity when
deciding whether an iterator is an appropriate input to an operation.

list(itr) and sum(itr) are both O(n) operations - the time they take
is proportional to the length of the input.
len(container) by contrast, is an O(1) operation - the time it takes
is independent of the length of the input.

There's no length independent way of calculating the length of an
arbitrary generator - it's an inherently O(n) operation. "sum(1 for x
in seq)" conveys that accurately, "len(x for x in seq)" does not.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list