Python copy list list

I am using python 3.4.1.
For one list, a=[1,2] , if I make a copy of it, b = a.copy() , when I change the elements in b , it will not change the elements in a .
However, when I define a list of lists (actually a matrix) a = [[1,2],[3,4]] , when I assign b = a.copy() . What I do to list b really affects a .
I checked their addresses, they are different.
Can someone tell me why?

ps: What I did was b[0][0] = x , and the element in was also changed.

+6
source share
3 answers

In the docs for copy module:

The difference between shallow and deep copy is applicable only for compound objects (objects that contain other objects, such as lists or class instances):

  • A shallow copy creates a new compound object, and then (as far as possible) inserts links into it into the objects found in the original.
  • A deep copy creates a new compound object, and then recursively inserts copies of the objects found in the original into it.

When you call plain copy.copy() , you do a shallow copy. This means that in the case of a list of lists, you will receive a new copy of the external list, but it will contain the original internal lists. Instead, you should use copy.deepcopy() , which will create a new copy of both the external and internal lists.

The reason you did not notice this in the first example of using copy([1,2]) is because primitives such as int are immutable and therefore it is not possible to change their value without creating a new instance. If the contents of the list were instead a modified object (for example, lists or any user-defined object with mutable members), any mutation of these objects would be seen in both copies of the list.

+5
source

Perhaps understanding the list as such:

 new_list = [x[:] for x in old_list] 

... although if your matrices are deeper than one layer, list comprehension is probably less elegant than just using deepcopy .

edit - a shallow copy, as indicated, will still contain references to objects within the list. For example...

 >>> this = [1, 2] >>> that = [33, 44] >>> stuff = [this, that] >>> other = stuff[:] >>> other [[1, 2], [33, 44]] >>> other[0][0] = False >>> stuff [[False, 2], [33, 44]] #the same problem as before >>> this [False, 2] #original list also changed >>> other = [x[:] for x in stuff] >>> other [[False, 2], [33, 44]] >>> other[0][0] = True >>> other [[True, 2], [33, 44]] >>> stuff [[False, 2], [33, 44]] #copied matrix is different >>> this [False, 2] #original was unchanged by this assignment 
+2
source

It is very simple, just do this:

 b = a 

Exemple:

 >>> a = [1, 2, 3] >>> b = a >>> b.append(4) >>> b [1, 2, 3, 4] >>> a [1, 2, 3, 4] 
-3
source

Source: https://habr.com/ru/post/982913/


All Articles