Question

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 !

Was it helpful?

Solution

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

OTHER TIPS

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]
>>> 

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top