Search code examples
pythonlistperformancecopy

Which method to copy a flat list is faster: comprehension, slice, or copy.copy?


Say I want to make a shallow copy of a list in python. Which method is fastest?

I can think of

  • copy.copy(l)
  • l[:]
  • [x for x in l]
  • list(l)

This question is specifically about the relative speed of making a shallow copy of a list in Python. Specifically, I am interested in CPython.


Solution

  • Tested in jupyter notebook, python 3.8

    l = list(range(10000))
    %%timeit
    [x for x in l]
    # 175 µs ± 5.23 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
    
    %%timeit
    copy.copy(l)
    # 22.6 µs ± 365 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
    
    %%timeit
    l[:]
    # 22 µs ± 1.28 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
    
    %%timeit
    list(l)
    # 21.6 µs ± 558 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
    

    So they're all the same except the list comprehension, which is far slower.