Home > other >  Novice confused about python list behavior, ask ace to reassure
Novice confused about python list behavior, ask ace to reassure

Time:01-24

By two different ways to create two two-dimensional list, respectively to the list of two-dimensional second list add two elements, but two two-dimensional list to get different results, only one of them meet the expected results, ask ace to solve, thank you!
The source code below
 list5=[5] [0] * * 4 
List6=[[0 for I in range (5)] for I in range (4)]
Print (list5)
Print (list6)
List5 [2]. The extend ([44, 65])
List6 [2]. The extend ([44, 65])
Print (list5)
Print (list6)


Results the following
[[0, 0, 0, 0, 0] to [0, 0, 0, 0, 0] to [0, 0, 0, 0, 0] to [0, 0, 0, 0, 0]]
[[0, 0, 0, 0, 0] to [0, 0, 0, 0, 0] to [0, 0, 0, 0, 0] to [0, 0, 0, 0, 0]]
[[0, 0, 0, 0, 0, 44, 65], [0, 0, 0, 0, 0, 44, 65], [0, 0, 0, 0, 0, 44, 65], [0, 0, 0, 0, 0, 44, 65]]
[[0, 0, 0, 0, 0] to [0, 0, 0, 0, 0] to [0, 0, 0, 0, 0, 44, 65], [0, 0, 0, 0, 0]]

CodePudding user response:

Python list has a shallow and deep copy of the problem, you can charge on the Internet,
List5 way should be shallow copy, although the copy list of a few, but they all point to the same address, so change the one, the other will become the same,
List6 way should be a deep copy, is to generate a new list of objects, the address of each list item is different, although the values look identical,
Detailed information can see online articles,

CodePudding user response:

List5 assignment is different from list6, list5 sublists point to the same memory address, and through the for loop to list6 assignment, every child list to different memory address, so the results will be different,
  • Related