Python Forum
Why do the lists not match? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Why do the lists not match? (/thread-40253.html)



Why do the lists not match? - Alexeyk2007 - Jun-29-2023

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



RE: Why do the lists not match? - snippsat - Jun-29-2023

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]]



RE: Why do the lists not match? - Alexeyk2007 - Jun-29-2023

Thank you!


RE: Why do the lists not match? - ICanIBB - Jul-01-2023

Because c is [[1,0], [1,0]] after step 9