Interesting list() un-optimization

Tim Chase python.list at tim.thechases.com
Thu Mar 7 04:57:35 CET 2013


On 2013-03-06 22:20, Roy Smith wrote:
> I stumbled upon an interesting bit of trivia concerning lists and
> list comprehensions today.

I agree with Dave Angel that this is interesting.  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 :-)

-tkc


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)

print "Ensuring we can iterate over it:"
for x in Foo():
    print x

print "\nJust call list():"
lst = list(Foo())
print lst

print "\nCall list(iter())"
lst = list(iter(Foo()))
print lst



More information about the Python-list mailing list