3

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?

martineau
  • 119,623
  • 25
  • 170
  • 301
amandi
  • 263
  • 2
  • 4
  • 7

6 Answers6

4

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I have similar question regarding python tuples. It says" A tuple can not be changed in any way once it is created.".But when i do following t1=(4,5,8,2,3) t1=t1+(7,1) print(t1) the tuple is changing as (4, 5, 8, 2, 3, 7, 1). why is that? what is really mean by tuple is immutable? – amandi Jun 13 '14 at 17:55
3

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]
Maciej Gol
  • 15,394
  • 4
  • 33
  • 51
1

Yes. l1+[30] creates a new list that is a concatenation of both lists. That's how + works on lists.

freakish
  • 54,167
  • 9
  • 132
  • 169
1

Yes, they are mutable.

In your second example you are overwriting the value of l1 with a new list, rather than modifying the object it refers to.

To modify the original list, you could use the += operator:

l1 += [30]
grc
  • 22,885
  • 5
  • 42
  • 63
1

Lists are mutable in python, but adding two lists will create a new object. You can verify if two objects are the same by checking their id. For instance:

In [1]: list1 = [1, 2]
In [2]: list2 = [3]

In [3]: id(list1)
Out[3]: 4359455952

In [4]: id(list2)
Out[4]: 4358798728

# Creates a new list
In [5]: list1 = list1 + [42]

In [6]: list1
Out[6]: [1, 2, 42]

# The id of the list1 is different
In [7]: id(list1)
Out[7]: 4359456024

# Mutate the list1 by appending an integer
In [8]: list1.append(53)

# The object is the same.
In [9]: id(list1)
Out[9]: 4359456024

Regards,

Pablo Navarro
  • 8,244
  • 2
  • 43
  • 52
1

When you declare L2 you are declaring a reference to an object (the list) and when you redeclare L1 you are creating a new list and changing what L1 references. So in the end L2 references what started as L1 and L1 now references a new object.

Tim.DeVries
  • 791
  • 2
  • 6
  • 21