-2

I have a list

arr = [1, 2, 3, 4, 5]

I create a different list that should have the same values as arr by assigning arr to arr2:

arr2 = arr

I assumed that arr and arr1 are different variables.

But when I perform a pop action on either one of those lists, the other list gets affected too.

What is the best way to approach this problem if I don't want to hard code values into a variable that should have the values of an already existing variable?

>>> arr = [1, 2, 3, 4, 5] 
>>> arr1 = arr 
>>> arr.pop(0) 
>>> print(arr) 
[2, 3, 4, 5] 
>>> print(arr1) 
[2, 3, 4, 5]
Tom Karzes
  • 22,815
  • 2
  • 22
  • 41
  • arr=[1,2,3,4,5] arr1=arr arr.pop(0) print(arr) [2,3,4,5] print(arr1) [2,3,4,5] – user3338757 Jun 07 '19 at 14:58
  • 4
    *"I create a different list"* - no, you don't. You have two identifiers referencing the same list object. See e.g. https://nedbatchelder.com/text/names.html – jonrsharpe Jun 07 '19 at 15:01
  • got the answer from the following link https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list – user3338757 Jun 07 '19 at 15:21

1 Answers1

-1
import copy
arr1 = copy.copy(arr)

Now if you change anything in arr, it won't affect arr1 and vice versa.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Abhilash V
  • 69
  • 3