+ 3

Why is the difference between output a and b? Why in output b is second '5'?

a=[[0,0],[0,0]] print(a) b=[[0]*2]*2 print(b) # a is the same what is b? a[0][0]=5 print(a) # output [[5,0][0,0]] b[0][0]=5 print(b) # output [[5,0][5,0]]

17th Jun 2020, 9:07 PM
Paweł Malewicz
Paweł Malewicz - avatar
3 ответов
+ 4
Those are reference problems. Lists store adresses to other lists. By using *, those addresses get copied, so you end up with another list that contains the same addresses. It sounds messy, but you can wrap your head around it after a while. I hope this will help you: https://code.sololearn.com/c89ejW97QsTN/?ref=app
17th Jun 2020, 10:29 PM
HonFu
HonFu - avatar
+ 3
It's definitely worth your time, figuring these things out, because they really come up all the time, in the most unexpected situations.
20th Jun 2020, 11:04 AM
HonFu
HonFu - avatar
+ 2
Thank you. The description makes sense for me. I need some time to analyze the attached code however I come back to this one for sure.
20th Jun 2020, 10:50 AM
Paweł Malewicz
Paweł Malewicz - avatar