Copy lists in Python

Copy a list to another

>>> myList=[1,2,3]
>>> myCopy = myList[:]
>>> myCopy
[1, 2, 3]
>>> myList=[1,2,3]
>>> myCopy = myList
>>> myCopy[0]=5
>>> myList
[5, 2, 3]

Copy lists including mutable items

>>> import copy
>>> myList=[[1],[1,2],[1,2,3]]
>>> myCopy = copy.deepcopy(myList)
>>> myCopy
[[1], [1, 2], [1, 2, 3]]
>>> myList=[[1],[1,2],[1,2,3]]
>>> myCopy=myList[:]
>>> myCopy[1][0]=6
>>> myList
[[1], [6, 2], [1, 2, 3]]

See also


Last update : 06/11/2018