Search code examples
pythonmutable

Copying mutable lists in python


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 !


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