0
How can someone 'copy' a list and change the elements in the 'copied' list and not affect the original one? Thanks in advanceđ
I created a list and copied it. Changing the elements in the second list, affected the original one. đđ Guns = ["SPITTER", "STING"] Guns2 = Guns Guns2[0] = "VENOM" print(Guns) đ["VENOM", "STING"] print(Guns2) đ["VENOM", "STING"]
4 Respostas
+ 2
here is a way to get around it
first = ["apples", "orange"]
second = list(first)
second[0] = "grapes"
print(first)
print(second)
>>>
["apples", "orange"]
["grapes", "orange]
concept behind how guns2 is connected to guns is that when you write the instruction
guns2 = guns
you're stating that guns2 represents guns not the value of guns.
so whenever guns2 or guns change a value
the other variable would change as well.
so changing the instruction into
guns2 = list(guns)
guns2 will then contain the value of guns.
+ 3
if you like you can also use copy:
import copy
Guns = ["SPITTER", "STING"]
Guns2 = copy.copy(Guns)
Guns2[0] = "VENOM"
print(Guns)
print(Guns2)
# output:
'''
['SPITTER', 'STING']
['VENOM', 'STING']
'''
0
Thanks a lotđđ