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

Nick Coghlan ncoghlan at gmail.com
Sat Oct 4 13:42:34 CEST 2014


On 4 October 2014 01:36, Mark Young <marky1991 at gmail.com> wrote:
> Why do you think len is an inherently O(1) operation? Sure, on array-based
> things it is, but for an arbitrary collection, the only logical assertion is
> that it's O(n). (For some containers, like arrays, it might be O(1) as well,
> but you can't assume that in general)

It's not a hard requirement (it can't be), but it *is* a rather strong
convention that checking something's length should be an O(1)
operation.

A non-specialised container that doesn't implement len() as an O(1)
operation in Python would quite likely end up with users asking for
the length to be cached to make it O(1). In particular, it's generally
expected that "if obj:" should be O(1), and that's likely to fall back
to __len__() for most container types.

Regards,
Nick.

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


More information about the Python-ideas mailing list