1

While reading about slicing a list; i got stuck here:-

a = [1, 3, 5]
b = a[:]
a[:] = [x**2 for x in a]
a[:] = [0]
print(b) # output --> [1,3,5]

And this:-

a = [1, 3, 5]
b = a
a[:] = [x**2 for x in a]
a[:] = [0]
print(b) # output --> [0]

I know that b = a[:] is making a copy of list a but then what b=a is doing in the second example? And when printing the outputs, in the first case b doesn't get modified but get modified in second one. What is the reason for this behavior? I am not asking about how to do slicing, but wondering why both the codes mentioned are behaving strangely and differently.

Vicrobot
  • 3,795
  • 1
  • 17
  • 31

2 Answers2

3

b = a is an assignment by reference: it makes the variable b point at the same list that variable a is pointing to. So when you update the contents of that list on the next line, with a[:] = ... then both a and b are pointing to the updated list.

If the next line had been a = [x**2 for x in a] (instead of a[:] = ...) that would have created a new list [1,9,25] and assigned the variable a to point at it, leaving b still pointing at the original list.

Richard Inglis
  • 5,888
  • 2
  • 33
  • 37
1

When you do b = a, you simply creating a reference to the variable a and this reference is named b. A reference is just another name for the same object. You are not creating a copy of the variable a. Therefore, if you modify b, it modifies a as well and vice versa.

However, if you do b = a[:], you are creating a shallow copy of the variable a and assigning it to a new variable called b. Since b is a copy, modifying either one of them, won't change the other.

That is precisely why you get two different answers when printing b at the end.