Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why do the lists not match?
#1
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
Reply
#2
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]]
Reply
#3
Thank you!
Reply
#4
Because c is [[1,0], [1,0]] after step 9
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Split dict of lists into smaller dicts of lists. pcs3rd 3 2,387 Sep-19-2020, 09:12 AM
Last Post: ibreeden
  sort lists of lists with multiple criteria: similar values need to be treated equal stillsen 2 3,296 Mar-20-2019, 08:01 PM
Last Post: stillsen

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020