Jun-29-2023, 06:00 PM
(This post was last modified: Jun-29-2023, 06:01 PM by Alexeyk2007.)
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
Why do the lists not match?
|
Jun-29-2023, 06:00 PM
(This post was last modified: Jun-29-2023, 06:01 PM by Alexeyk2007.)
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]]
Jun-29-2023, 07:14 PM
Thank you!
Jul-01-2023, 09:19 PM
Because c is [[1,0], [1,0]] after step 9
|
|
Possibly Related Threads… | |||||
Thread | Author | Replies | Views | Last Post | |
Split dict of lists into smaller dicts of lists. | pcs3rd | 3 | 3,273 |
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 | 4,981 |
Mar-20-2019, 08:01 PM Last Post: stillsen |