Python Forum

Full Version: Why do the lists not match?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
b = [0 for i in range(2)]
a = [b for k in range(2)]

c = a
d = [[0, 0], [0, 0]]

print(c == d)  # True

c[0][0] = 1
d[0][0] = 1
print(c == d)  # False
Because the way create a(list of list) the two list will point to the same memory location.
Move it over to c it still will point to the same memory location.
>>> b = [0 for i in range(2)]
>>> a = [b for k in range(2)]
>>> c = a
>>> [id(i) for i in c]
[247932352, 247932352]

>>> help(id)
Help on built-in function id in module builtins:

id(obj, /)
    Return the identity of an object.
    
    This is guaranteed to be unique among simultaneously existing objects.
    (CPython uses the object's memory address.)
If make it like this,then lists will not point to same place in memory.
>>> c = [[0 for _ in range(2)] for _ in range(2)]
>>> c
[[0, 0], [0, 0]]
>>> [id(i) for i in c]
[1953346963520, 1953346964224]

>>> d = [[0, 0], [0, 0]]
>>> c[0][0] = 1
>>> d[0][0] = 1
>>> c
[[1, 0], [0, 0]]
>>> d
[[1, 0], [0, 0]]
Thank you!
Because c is [[1,0], [1,0]] after step 9