make a copy of list in python
Methods to copy a list in python
As s freshman using python, It’s easy to be confused when copying a list
. Here are some methods to make copy from originalList
to targetList
which are from the blog page, [Python]列表复制的几种方法. they are:
# python code
# No.1 DON'T USE THIS.
targetList = originalList # DON'T USE THIS, IT MAKES A CLONE NOT A COPY.
# No.2
targetList = originalList[:]
# No.3
targetList = list(originalList)
# No.4
targetList = originalList*1
# No.5
import copy
targetList = copy.copy(originalList)
# No.6
import copy
targetList = copy.deepcopy(originalList)
The perplexing point
When copying a list, one or more element of which is list, attentions should be payed to. In this case, the first 5 methods mentioned previously would not work as you want, only the 6th method mentioned previously could work exactly as you want.
Explain copying 2-dimensional list
by applying method No.1 targetList = originalList
, one made a clone of the list originalList
. the two variables share the same RAM units. One changes targetList[2]
, one changes originalList[2]
. One changes originalList[2]
, one changes targetList[2]
. It just like pointer in C language. targetList
is the list name and targetList
is the pointer name.
by applying method No.2~No.5, each element of targetList
stored in a different RAM unit from elements of originalList
. But, the content of the RAM units may be same. Saying, the two lists are physically different in 1st level, storing the same infomation. If the element is a number, it’s ok. If the element is another list, the element of targetList
and its originalList
counterpart have the same content, pointing to the same list(sublist). If one modified the content of the sublist, as the sublist is the sublist of both lists, both lists changed.
Still perplexing?
Here is a simple method getting things done. You just need:
import copy
targetList = copy.deepcopy(originalList)
then, everything is done.