Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are lists mutable? [duplicate]

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?

like image 225
amandi Avatar asked Oct 13 '25 06:10

amandi


2 Answers

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.

like image 138
Barmar Avatar answered Oct 14 '25 19:10

Barmar


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]
like image 42
Maciej Gol Avatar answered Oct 14 '25 20:10

Maciej Gol