What is the fastest way to make a shallow copy of list in Python3.5+?
Asked Answered
K

1

13

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]
  • and others...

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?

Korte answered 17/12, 2017 at 21:9 Comment(0)
K
30

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: enter image description here

But at the len(some_list) < 1000 we have a clear winner, and it is [*some_list]:enter image description here

The measurments were performed with Python 3.6.3, Windows 7.

Korte answered 17/12, 2017 at 21:9 Comment(4)
Those lines converge, so it seems that the correct answer is in fact "it is all the same". Except for the very small lists, in which case the answer is "who cares" ;)Sprocket
@Sprocket People with very many very small lists, that's who cares :-) (maybe). Another option is some_list * 1, which I find noteworthy as it's the second-fastest in my own tests (only beaten by [*some_list]) and short.Vocabulary
unless the copy is the inner loop of some other, repeatedly executed, loop ..Wellfounded
@Sprocket I care. This is exactly what I needed to know.Inclement

© 2022 - 2024 — McMap. All rights reserved.