The are several alternatives to make a shallow copy of a list
in Python 3.5+. The obvious ones are:
some_list.copy()
some_list[:]
list(some_list)
[*some_list]
Which method is the fastest?
NOTE: While this question is related to a "copy of the list", it concerns only performance in Python 3.5+. If you need an answer to the question of "Why you need a copy of a list in Python?", or "What is the difference between shallow and deepcopy of a list in Python?" read the following: How to clone or copy a list?
The only reasonable answer to this question is to compare their execution time. Since the question concerns Python 3.5+, I will recall that in Python 3.5 the PEP 448 -- Additional Unpacking Generalizations was approved and it turns out that [*some_list]
is the fastest way to make a shallow copy of the list in Python 3.5+, the measurements are presented below. Of course there are many more ways to make a copy, but I will focus on the following ones:
some_list.copy()
some_list[:]
list(some_list)
[*some_list]
from copy import copy; copy(some_list)
Keep in mind these times are relative to one another, but the trend should be similar.
As can be seen from the plot below, all variants behave roughly the same when the len(some_list) >= 1000
:
But at the len(some_list) < 1000
we have a clear winner, and it is [*some_list]
:
The measurments were performed with Python 3.6.3, Windows 7.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With