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

Cathal Garvey cathalgarvey at cathalgarvey.me
Fri Oct 3 17:48:33 CEST 2014


Well, he said for _containers_, for which we assume a length attribute
has been tallied all along; calling len() on a container should just
access this tally, making it minimally intensive.

For iteration-enabled classes, you can implement a __len__() magic
method which returns whatever you like, so if you can make predictions
about the length of an iterable class, even if the values are generated
on the fly, then you can implement this to make it return the value
without much computation.

Some builtin generators appear to do just this:

In [10]: %timeit  len(range(100))
1000000 loops, best of 3: 1.27 µs per loop

In [11]: %timeit  len(range(1000))
1000000 loops, best of 3: 1.51 µs per loop

In [12]: %timeit  len(range(100000))
1000000 loops, best of 3: 1.59 µs per loop

In [13]: %timeit  len(range(10000000))
1000000 loops, best of 3: 1.58 µs per loop

On 03/10/14 16:36, Mark Young 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)​
> 
> 
> 
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
> 

-- 
Twitter: @onetruecathal, @formabiolabs
Phone: +353876363185
Blog: http://indiebiotech.com
miniLock.io: JjmYYngs7akLZUjkvFkuYdsZ3PyPHSZRBKNm6qTYKZfAM
-------------- next part --------------
A non-text attachment was scrubbed...
Name: 0x988B9099.asc
Type: application/pgp-keys
Size: 6176 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141003/d456ee46/attachment-0001.key>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141003/d456ee46/attachment-0001.sig>


More information about the Python-ideas mailing list