0

How not to change value of a list???

>>> a=range(0,5)
>>> b=10
>>> c=a
>>> c.append(b)
>>> c
[0, 1, 2, 3, 4, 10]
>>> a
[0, 1, 2, 3, 4, 10]

Until today i didn't know that lists in python are mutable !

luzik
  • 673
  • 2
  • 7
  • 15
  • "Mutable" just means you can change it; `c.append(b)` would not work if lists were not mutable. I think you were just unaware that `c=a` does not create a new list distinct from the one referenced by `a`. – chepner Dec 04 '13 at 14:13

3 Answers3

9

Followng statement make c reference same list that a reference.

c = a

To make a (shallow) copy, use slice notation:

c = a[:]

or use copy.copy:

import copy

c = copy.copy(a)

>>> a = range(5)
>>> c = a[:]  # <-- make a copy
>>> c.append(10)
>>> a
[0, 1, 2, 3, 4]
>>> c
[0, 1, 2, 3, 4, 10]
>>> a is c
False
>>> c = a    # <--- make `c` reference the same list
>>> a is c
True
falsetru
  • 357,413
  • 63
  • 732
  • 636
1

You are making c reference the same list as a. So to make a shallow copy, use list()

>>> a = [1,2,3]
>>> b = list(a)
>>> b
[1, 2, 3]
>>> b.append(4)
>>> a
[1, 2, 3]
>>> b
[1, 2, 3, 4]
>>> 
Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
1

You can transform the list into a tuple, which is an immutable list.

Dive into Python book :

A tuple is an immutable list. A tuple can not be changed in any way once it is created.

Also

Tuples can be converted into lists, and vice-versa. The built-in tuple function takes a list and returns a tuple with the same elements, and the list function takes a tuple and returns a list. In effect, tuple freezes a list, and list thaws a tuple.

Bogdan Goie
  • 1,257
  • 1
  • 13
  • 21