Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 644
godaygo Avatar asked Dec 17 '17 21:12

godaygo


1 Answers

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.

like image 83
godaygo Avatar answered Nov 15 '22 05:11

godaygo