Interesting list() un-optimization

Christian Heimes christian at
Thu Mar 7 17:20:52 CET 2013

Am 07.03.2013 17:00, schrieb Ian Kelly:
> On Thu, Mar 7, 2013 at 4:22 AM, Wolfgang Maier
> <wolfgang.maier at> 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__()



More information about the Python-list mailing list