0

Python 3 , list of lists initialisation

take a look at this code : https://code.sololearn.com/c076UQaTbPk5 Can you help me figure out why the output differs?

10th Apr 2020, 4:45 PM
Giulia Zangirolami
Giulia Zangirolami - avatar
6 odpowiedzi
+ 4
This resembles your situation: https://www.sololearn.com/Discuss/1327452/?ref=app Basically when you [...]*3 all the lists inside "a" share the same space in memory so they're the same thing, you can check that by comparing id(a[0]), id(a[1]), id(a[2]) (which I shamefully didn't myself) So when you append '1', '2', ... to each element of "a" they also append to the other lists inside "a", and there's your unexpected behaviour. Also, note: >>> a = [] >>> b = a >>> a.append(1) >>> b.append(2) >>> a [1, 2] >>> b [1, 2]
10th Apr 2020, 5:30 PM
Zuke
Zuke - avatar
+ 2
Thank you very much Zuke , your explanation was very clear :) and thanks to all you guys answering
10th Apr 2020, 5:34 PM
Giulia Zangirolami
Giulia Zangirolami - avatar
+ 1
it looks like this statement a = [[]]*5 use the same object 5 times. just do this test print(a[0] is a[1])#output True but b = [[]for _ in range(5)] creates 5 different objects. print(b[0] is b[1]) #output False
10th Apr 2020, 5:34 PM
John Robotane
John Robotane - avatar
+ 1
a = [list()]*5 # this behaves strangely when appended b = [[]for _ in range(5)] # this behaves as expected print(a) print(b) print(a == b) # Till here everything is equal # a == b because a and b contains both 5 empty lists, but a containd 5 times the same list object (same reference in memory), while b contains 5 different lists (different references in memory). c = [] for i in range(5): c.append("12345") for j in range(5): a[j].append(c[i][j]) # here you access the same list at each iteration (a[n] == a[m]) c = [] for i in range(5): c.append("12345") for j in range(5): b[j].append(c[i][j]) # here you access a different list at each iteration print(a) print(b) print(a == b) # different result
10th Apr 2020, 5:35 PM
visph
visph - avatar
0
Game Play hi(?)
11th Apr 2020, 10:46 PM
Giulia Zangirolami
Giulia Zangirolami - avatar
- 1
Hello
11th Apr 2020, 1:50 PM
Game Play
Game Play - avatar