Need explain for py code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Need explain for py code

Hello, I need some explain for this code a=[1,[2,3]] b=a[:] a[0]=3 a[1][1]=5 print(b) The answer was [1,[2,5]] I got this wrong cause I expected that b will be linked to a and get same list value. So what exactly mean when b=a[:] and what it different than b=a Thanx in advance ^^

22nd Feb 2020, 6:04 PM
Violet Wave
Violet Wave - avatar
3 Answers
+ 3
a[0] is an integer. integers are copied by value -> no impact on b a[1] is a list. lists are copied by reference a[1] and b[1] are identical -> impact on b
22nd Feb 2020, 6:17 PM
Oma Falk
Oma Falk - avatar
+ 4
b=a means: b is a further name for a b=[:] means b is a copy of a but a different object. copy is tricky : copying a number makes a new number but copying a list means copying reference to list. So the list [2,5] in a and b is the same object.
22nd Feb 2020, 6:07 PM
Oma Falk
Oma Falk - avatar
+ 3
Oki got it now ^^ thank you so much
22nd Feb 2020, 6:20 PM
Violet Wave
Violet Wave - avatar