It is said Lists in python are mutable. When I write code like below,
l1=[6,7,8,4,3,10,22,4]
l2=l1
l1.append(30)
print(l1)
print(l2)
both l1 and l2 prints the same list: [6, 7, 8, 4, 3, 10, 22, 4, 30]
But when i give code like below,
l1=[6,7,8,4,3,10,22,4]
l2=l1
l1=l1+[30]
print(l1)
print(l2)
l1
prints --> [6, 7, 8, 4, 3, 10, 22, 4, 30]
l2
prints --> [6, 7, 8, 4, 3, 10, 22, 4]
So, now there references have changed. So are lists in python really mutable?
The +
operator is not a mutator, it returns a new list containing the concatenation of the input lists.
On the other hand, the +=
operator is a mutator. So if you do:
l1 += [30]
you will see that both l1
and l2
refer to the updated list.
This is one the subtle differences between x = x + y
and x += y
in Python.
Lists in Python are mutable. The reason for the references' change is that the +
operator does create a new list with values of it's operands. On the other hand, the +=
operator does the addition in-place:
>>> l1 = [1,2,3]
>>> l2 = l1
>>> l1 += [30]
>>> l2
[1,2,3,30]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With