b = [[1,2],[1,2]]
print(id(b[0])) # 139948012160968
print(id(b[1])) # 139948011731400
b = [[1,2]]*2
print(id(b[0])) # 139948012161032
print(id(b[1])) # 139948012161032
`id() shows the object's ID or the memory location in Python.
When you do b = [[1,2]]*2
you are basically saying let's point to the same object twice and store it in b in a list.
When you do b = [[1,2],[1,2]]
you are basically saying let me get two different objects and put them in a list and let b reference the list.
So for the latter example, of course you are going to get that output since they are the same object you are changing. You can think of it as me giving you the same address to a house and I have the same address I gave you. We end up at the same place and what ever changes we make to the house, we see it together.
Edited for comment:
Correct! They are changing how the memory is handled but the values are the same.
==
tests if the values are the same. is
tests if the objects are the same. so in our case:
#First case:
print(b[0] == b[1]) #true
print(b[0] is b[1]) #false
#second case:
print(b[0] == b[1]) #true
print(b[0] is b[1]) #true
Edited second time for second comment!~
import copy
x = [1,2]
b = [copy.copy(x) for i in range(3)]
print(id(b[0])) #140133864442248
print(id(b[1])) #140133864586120
print(id(b[2])) #140133864568008
print(b) #[[1, 2], [1, 2], [1, 2]] you can extend range to 256.
If you want a unique object and want to copy it from another object, try using copy. It makes a new object with the same values.
Edited again using one of my favorite function sum
:
This is more or less redundant and it might confuse you some more, but sum
also works too.
x = [1,2]
b = [sum([x],[]) for i in range(3)]
print(id(b[0])) #140692560200008
print(id(b[1])) #140692559012744
print(b) #[[1, 2], [1, 2], [1, 2]]
Will return different instances in the object. I only point this is just in case you don't want to import copy or import anything.