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.