+ 1

Problem with lists

Can someone explain why the output of the code is [1, [3, 6]] not [9, [3, 6]]? a = [1, [3,4]] b = a[ : ] a[0] = 9 a[1][1] = 6 print(b)

2nd Nov 2018, 4:09 PM
Risto V.
Risto V. - avatar
7 Réponses
+ 5
As i remember, only numbers, strings, booleans and None are stored specifically, others are treated as objects, so they can't be copied and return the reference when you assign it to a variable🤔 For example, a = 3 b = a # pass by value c = "test" d = c # pass by value e = [1,2,3] f = e # pass by reference when you use b=a[:] you can think it like b = [None]*len(a) for p in range(len(a)): b[p] = a[p] if a[p] is an object, it gets the reference, not only its value
2nd Nov 2018, 6:12 PM
Flandre Scarlet
Flandre Scarlet - avatar
+ 3
Like TurtleShell said, a[:] returns a shallow copy of a, that is, it just copies references to the objects in a. For immutable objects like integers, there's no noticeable difference, but mutable objects like lists would change whenever the original ones are changed. So changing a[0] doesn't affect b[0], as it's an integer. But a[1] is a list, and its modifications would be reflected in b[1].
2nd Nov 2018, 5:47 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 2
Nested lists don’t get deep copied I guess?
2nd Nov 2018, 4:34 PM
TurtleShell
TurtleShell - avatar
+ 1
a[:] instead of just a deep copies the list meaning b gets a brand new list instead of a reference to a if you want a and b to share a list just remove the [:] like so: a = [1, [3, 4]] b = a
2nd Nov 2018, 4:14 PM
TurtleShell
TurtleShell - avatar
+ 1
Got the picture. Thanks :)
2nd Nov 2018, 5:52 PM
Risto V.
Risto V. - avatar
+ 1
Thank you all for your answers. I think we reached to the bottom of this! ;) Have a good wknd!
2nd Nov 2018, 6:37 PM
Risto V.
Risto V. - avatar
0
I understand that b is copy of a, but can't fathom why a[1][1] = 6 changes the copy and a[0] = 9 not.
2nd Nov 2018, 4:32 PM
Risto V.
Risto V. - avatar