Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
about List question
#1
The last line I expected is [[1], [0], [0], [0]],
But as below the result is [[1], [0], [1], [0]],
Is This OK?
>>> a=[0,0]
>>> a
[0, 0]
>>> a=a*2
>>> a
[0, 0, 0, 0]
>>> a[0]=1
>>> a
[1, 0, 0, 0]
>>> 
>>> a=[[0],[0]]
>>> a
[[0], [0]]
>>> a = a *2
>>> a
[[0], [0], [0], [0]]
>>> a[0][0] = 1
>>> a
[[1], [0], [1], [0]]
Reply
#2
Every value in python is an instance of some class. An instance is like a box that contains data. In your example, the list [[0], [0], [0], [0]] contains only two instances of list because the instance at position 2 is the same as the instance at position 0 and similarly for positions 1 and 3.

One can get the identity of an instance with the function id() which returns an integer, for example
>>> a = [[0], [0]]
>>> for x in a:
...     print(id(x))
... 
140478940539432
140478940540656
>>> a = a * 2
>>> for x in a:
...     print(id(x))
... 
140478940539432
140478940540656
140478940539432
140478940540656
>>> a = [[0] for i in range(4)]
>>> for x in a:
...     print(id(x))
... 
140478940622648
140478940622720
140478940622792
140478940667984
>>>
>>> a = [[0], [0]]
>>> import copy
>>> a += [copy.copy(x) for x in a]
>>> for x in a:
...     print(id(x))
... 
140335687898376
140335687898312
140335687912328
140335687913032
When two instances have the same identity, they are the same instance.
Reply
#3
Thank for your kind reply.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020