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)
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) 
    
    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.
