0

It's possibly a easy question but I didn't find the solution in internet, possibly because I don't know how to search it, but I want to copy a list and change the copy without changing the original one, and I'm not managing to do it.

I let here a very simple example,

a=[1,2,3,4,5,6]
b=a

for i in range(6):
    b[i]=0
    
a ---> [0,0,0,0,0,0]
b ---> [0,0,0,0,0,0]

And I would like to mantain the original variable instead,

a ---> [1,2,3,4,5,6]
b ---> [0,0,0,0,0,0] 
Euler
  • 121
  • 6

1 Answers1

0

For not nested collections, you can use:

a = [1,2,3,4,5,6]
b = a.copy()  # or a[:]

for i in range(6):
    b[i] = 0

print(a)
print(b)

Output:

[1, 2, 3, 4, 5, 6]
[0, 0, 0, 0, 0, 0]

If you have nested collections, you can use deepcopy from copy module.

Corralien
  • 109,409
  • 8
  • 28
  • 52