+ 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 ^^
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
+ 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.
+ 3
Oki got it now ^^ thank you so much