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

13th Aug 2019, 10:03 AM
Martin Mururu
Martin Mururu - avatar
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.
13th Aug 2019, 10:19 AM
Shen Bapiro
Shen Bapiro - avatar
+ 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'] '''
13th Aug 2019, 2:42 PM
Lothar
Lothar - avatar
0
Thanks a lot🙏🙏
13th Aug 2019, 10:12 AM
Martin Mururu
Martin Mururu - avatar