+ 4

Could Someone explain this code please

What is the output of this code? a = [1, [2, 3]] b = a[:] a[0] = 3 a[1][1] = 5 print(b) The answer is [1, [2, 5]]!! but how?? Thanks

30th Dec 2018, 12:17 PM
Ingrid Horatius
Ingrid Horatius - avatar
7 Réponses
+ 14
Lists are tricky, indeed... ;) b gets assigned anew with values of a. So it's now [1, [2, 3]]. Mind, that it actually means that the first element being an integer, gets copied, but the second element, which is a list [2, 3] gets *referenced* to. Then a[0] is changed, which does not influence b. *But* when a[1][1] is changed, it changes the value in the memory location which b[1] references to. This is why when a[1][1] is assigned to 5, both a[1] and b[1] point to [2, 5]. So b is now [1, [2, 5]]
30th Dec 2018, 12:33 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 4
# If you want the output to be [1, [2, 3]] use this code from copy import deepcopy a = [1, [2, 3]] b = deepcopy(a) a[0] = 3 a[1][1] = 5 print(b)
30th Dec 2018, 1:48 PM
Shuaib Nuruddin
Shuaib Nuruddin - avatar
+ 3
@Kuba, Thank you! I didn't know this property of list but now it makes sense :)
30th Dec 2018, 12:42 PM
Ingrid Horatius
Ingrid Horatius - avatar
+ 2
Ingrid No problem. Kindly please mark my answer as best (✔️ on the left) if it helped you, keeps my motivation up ;)
30th Dec 2018, 1:22 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 1
Is a[:] equal to copy(a) or why does the integer get copied? I remember learn that lists are always passed by reference.
31st Dec 2018, 10:25 AM
Chris
Chris - avatar
+ 1
Tricky lists :)
1st Jan 2019, 5:39 AM
Edwing123
Edwing123 - avatar
+ 1
There are different ways to copy a list, but some of them only create a shallow copy so it is modified when the original is modified https://code.sololearn.com/cV5e805UQ43A/?ref=app
1st Jan 2019, 1:15 PM
Laura Madrigal
Laura Madrigal - avatar