Computer Science · Ch 9 — Lists
Copying Lists
Copying Lists
Copying a list is one of the places where Python's behaviour surprises beginners: the "obvious" way — plain assignment — does not create a copy at all. Understanding why, and knowing the three ways to make a genuine copy, is the point of this section.
Assignment creates an alias, not a copy
The simplest-looking way to "copy" a list is to assign it to another name:
>>> first = [4, 5, 6]
>>> second = first
>>> first
[4, 5, 6]
>>> second
[4, 5, 6]
But the statement second = first does not create a new list. It merely makes first and second refer to the same list object — second becomes an alias of first. Because there is only one underlying list, any change made through either name shows up in the other:
>>> first.append(99)
>>> first
[4, 5, 6, 99]
>>> second # the "copy" changed too — same object
[4, 5, 6, 99]
Making a true copy (a clone)
To get a copy that is a distinct object — a clone whose later changes do not affect the original — Python offers three methods: slicing, the built-in list() function, and the copy() function from the copy library module.
Method 1 — slicing
A slice always builds a new list, so slicing the entire original ([:], both indices omitted) yields an independent duplicate. The pattern is:
newList = oldList[:]
For example:
>>> nums = [10, 11, 12, 13]
>>> clone = nums[:]
>>> clone
[10, 11, 12, 13]
Method 2 — the built-in list() function
list() called with a sequence builds a fresh list from its elements, so passing the old list produces a new one. The pattern is:
newList = list(oldList)
For example:
>>> colours = ['Red', 'Blue', 'Green']
>>> backup = list(colours)
>>> backup
['Red', 'Blue', 'Green']
Method 3 — copy.copy() from the copy library
Python's standard library module copy provides a copy() function for the same job. The module must be imported first:
import copy # import the library copy
newList = copy.copy(oldList) # use the copy() function of library copy
For example:
>>> import copy
>>> data = [2, 4, 8, 16]
>>> duplicate = copy.copy(data)
>>> duplicate
[2, 4, 8, 16]