}

How to copy or clone a list in Python3

Created:

Introduction

In python a variable is a reference to an object, if the variable was assigned to a list it is a reference to that list. We explain how to do a clone or a copy of a list.

Shallow copy versus DeepCopy

Shallow copy is a copy of the collection (or list) but it is not a copy of the objects that the collection contains. A deep copy also copies the elements of the collection.

A shallo copy of a list can be done like this:

import copy

original = [1,2,3, {'key': 'value'}]
# you can use the list to create a copy
copy1 = list(original)
# using a slick is a little tricker
copy2 = original[:]
# or you can use the copy module
copy3 = copy.copy(original)

# nwo you will see that the dict in all the copies has the same id
print(id(copy1[3])
print(id(copy2[3])
print(id(copy3[3])

If you want to do a deep copy you can use the deepcopy function from the copy module:

copy4 = copy.deepcopy(original)
# if you execute this code without closing python interpreter, you will see a new id for the dict
print(id(copy4[3])

Remeber that the deepcopy is more slow than the others copy.