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@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