Interesting list() un-optimization

Wolfgang Maier wolfgang.maier at
Thu Mar 7 12:22:56 CET 2013

Tim Chase <python.list <at>> writes:
> On 2013-03-06 22:20, Roy Smith wrote:
> > I stumbled upon an interesting bit of trivia concerning lists and
> > list comprehensions today.
> A little testing
> shows that this can be rewritten as
>   my_objects = list(iter(my_query_set))
> which seems to then skip the costly __len__ call.  Performance geeks
> are welcome to time it against the list-comprehension version 
> class Foo(object):
>     def __init__(self):
>         self.items = range(10)
>     def __iter__(self):
>         return iter(self.items)
>     def __len__(self):
>         print "Calling costly __len__"
>         return len(self.items)

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. In
most cases, such a workaround will not be feasible. Why should iter(QuerySet())
have a faster __len__() method defined than QuerySet() itself. Most likely,
iter(QuerySet()) just returns self anyway?

More information about the Python-list mailing list