Skip to content

Comment on Python: copying a list the right wayparent

Comments

With smaller lists, the results in my test change:

  >>> t1 = timeit.Timer('copy.copy(orig)','import copy;import random;orig = [random.randint(0,255) for r in xrange(10)];')
  >>> t2 = timeit.Timer('orig[:]','import copy;import random;orig = [random.randint(0,255) for r in xrange(10)];')
  >>> t3 = timeit.Timer('list(orig)','import copy;import random;orig = [random.randint(0,255) for r in xrange(10)];')

  >>> print t1.timeit(10000)
  0.0183310508728
  >>> print t2.timeit(10000)
  0.00397896766663
  >>> print t3.timeit(10000)
  0.00760293006897
Which is similar to those results.

This implies more setup cost for copy() and list(), but after that they're faster.

If not for noise, list() should always outperform copy() as copy() just calls list() internally (specifically type(l)(l)), and also incurs the cost of several interrupted function calls.

Also, the minor difference in slice vs. list() for large lists are likely platform dependent and highly sensitive to the details of branch prediction and cache.

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.