To explain how to create a copy of a list, let us first create a list. We will use a simple list of 4 items:
list1 = [1, 2, "a", "b"] |
Why do we want to create a copy anyway ? Well, because in Python, this assignement creates a reference (not a new independent variable):
list2 = list1 |
To convince yourself, change the first item of list2 and then check the content of list1, you should see that the two lists have been modified and contain the same items.
So, to actually copy a list, you have several possibilities. From the simplest to the most complex:
list2 = 1ist1[:] |
list2 = list(1ist1) |
import copy list2 = copy.copy(list1) |
import copy list2 = copy.deepcopy(list1) |
To convince yourself about the interest of the latter method, consider this list:
import copy list1 = [1, 2, [3, 4]] list2 = copy.copy(list1) list2[2][1] = 40 |
you should see that changing list2, you also changed list1. If this is not the intended behviour, you should consider using the deepcopy.
Please follow and like us:
2 Responses to Python: how to copy a list