Today I’d like to show you how to copy a list in three different ways. We’ll be focusing on shallow copies to keep things simple.
If you want, you can watch the video first:
First let’s create a list:
>>> a = [1, 2, 3]
Now let’s create another list, such that our a list is an element of it:
>>> b = ['a', 'b', a]
>>> b
['a', 'b', [1, 2, 3]]
If we now change an element in a, it’ll also change inside the b list:
>>> a[1] = 100
>>> a
[1, 100, 3]
>>> b
['a', 'b', [1, 100, 3]]
This is because of shared references. Both a and b reference the same object in memory, which is a mutable list. So, if we change an element of the list, the change will be made in place and now the last element of the b list will reference the same changed list.
And now let’s get back to our main topic. If you don’t want a change in a list to propagate to other places where you reference it, you can use a copy of the list, not the list itself.
Copy a List by Slicing
How to make a copy? Well, there are a couple of ways we can do it. The first method consists in slicing the whole list, so using a slice operator without the start index and the past index:
>>> a = [1, 2, 3]
>>> b = ['a', 'b', a[:]]
>>> b
['a', 'b', [1, 2, 3]]
Now we have two different lists but with the same values. We can check it using the == and is operators. The former states that the values are identical, the latter states that a is not the same object as b.
>>> a == b[2], a is b[2]
(True, False)
Anyway, if we now change an element in the original list, the copy will stay untouched:
>>> a[1] = 100
>>> a
[1, 100, 3]
>>> b
['a', 'b', [1, 2, 3]]
The copy Method
Another approach is to use the copy method on the list. The result is the same:
>>> a = [1, 2, 3]
>>> b = ['a', 'b', a.copy()]
>>> b
['a', 'b', [1, 2, 3]]
>>> a[1] = 100
>>> a
[1, 100, 3]
>>> b
['a', 'b', [1, 2, 3]]
The List Method
And one more method: we can pass our a list as an argument to the list method. The list method is usually used to convert objects of different types to lists, but actually, it’s a constructor method which creates a new list from the object passed as an argument. The result will be just like with the slice operator or the copy method:
>>> a = [1, 2, 3]
>>> b = ['a', 'b', list(a)]
>>> b
['a', 'b', [1, 2, 3]]
>>> a[1] = 100
>>> a
[1, 100, 3]
>>> b
['a', 'b', [1, 2, 3]]