Search code examples
pythonlist

Confused with changing lists


I'm stuck on this weird thing in Python where changing one thing messes with another. But with other variables it works fine.

How do I fix this?

example = [1, 2, 3,4,5]
new = example
new[3] = 6
print(example)

Which outputs [1, 2, 3, 6, 5] instead of [1,2,3,4,5]


Solution

  • When you set new = example, you're essentially making both of them refer to the exact same memory location. Hence any change made to one will be seen in the other. We can correct this with

    new = example[:]
    

    Although in some cases you need to

    import copy
    new = deepcopy(example)