Question about idioms for clearing a list

Raymond Hettinger python at rcn.com
Tue Feb 7 04:14:46 EST 2006


[bearophileHUGS at lycos.com]
> In my programs I have seen that there is another practical difference
> between version 1 and 3:
> (1) mylist[:] = []
> (3) mylist = []
> If you create a big mylist again and again many times, the version 1
> uses the memory more efficiently (probably less work for the garbage
> collector), and the program can be (quite) faster (this is true in some
> implementations different from CPython too).

There should be almost no difference in runtime between the two.  The
underlying CPython implementation caches list objects and is usually
able to create the new list without any calls to the memory allocator.
Likewise, garbage collection performs the same for both -- any objects
left with no references are immediately freed and any with only
circular references get freed when the collector runs.

The speed-up you observed likely occured with different code.  For
instance, given a large list, you can typically update or replace
individual elements faster than you can build-up a new list:

  L = [0] * 1000     # starting list
  for i in xrange(len(L)):
      L[i] += 1

beats:

  L = [0] * 1000     # starting list
  L = [L[i]+1 for i in xrange(len(L))]


Raymond




More information about the Python-list mailing list