0
mytest=[[False]*3]*2

In [46]: mytest
Out[46]: [[False, False, False], [False, False, False]]

In [47]: mytest[0][1]=True

In [48]: mytest
Out[48]: [[False, True, False], [False, True, False]]

On the other hand 

mytest=[ [False]*3 for i in range(2)]
In [53]: mytest[0][1]=True

In [54]: mytest
Out[54]: [[False, True, False], [False, False, False]]

On the first when in set [0][1], it sets at two places , but in second it sets correctly .. what is wrong with first assignment.

blhsing
  • 91,368
  • 6
  • 71
  • 106
subbu
  • 11
  • 3

1 Answers1

2

This is how Python handles objects. In your first example, the list mytest contains two [False, False, False] lists that are stored at the same memory location (i.e., both items in the list are pointing to the same memory location). When you change the one, the other is changed as well because simply they are both pointing to the same list in memory.

In the second example, and when you are using list comprehension the two lists [False, False, False] are two different objects pointing to different memory locations.

Proof

>>> mytest=[[False]*3]*2
>>> id(mytest[0])
4340367304
>>> id(mytest[1])
4340367304
>>> mytest=[ [False]*3 for i in range(2)]
>>> id(mytest[0])
4340436936
>>> id(mytest[1])
4340498512

The difference with the first and second statement is that your first statement will first evaluate [False] * 3 first which gives [False, False, False] and then *2 will create two references of that object ([False, False, False]). In the second example, you are creating a [False, False, False] each time.

Rafael
  • 7,002
  • 5
  • 43
  • 52