Interesting list() un-optimization

Christian Heimes christian at python.org
Thu Mar 7 11:20:52 EST 2013


Am 07.03.2013 17:00, schrieb Ian Kelly:
> On Thu, Mar 7, 2013 at 4:22 AM, Wolfgang Maier
> <wolfgang.maier at biologie.uni-freiburg.de> wrote:
>> Well, it skips the costly len() call because your iter(Foo()) returns
>> iter(range()) under the hood and list() uses that object's __len__() method.
> 
> Iterators do not generally have __len__ methods.
> 
>>>> len(iter(range(10)))
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> TypeError: object of type 'range_iterator' has no len()

But iterators have a length hint method that are used for some
optimizations and preallocations, too.

>>> i = iter(range(10))
>>> i.__length_hint__()
10

See http://www.python.org/dev/peps/pep-0424/

Christian




More information about the Python-list mailing list