-1

I have the below small code in Python where I am changing the value of list_one by using pop() function but I am not doing any changes in list_two. on printing list_one and list_two they both print the same results as mentioned below.

arr = [1,2,3,4,5]
list_one = arr
list_two = arr
list_one.pop(0)

print(list_one)
print(list_two)

Output:
[2, 3, 4, 5]
[2, 3, 4, 5]

Can someone please help me understand why list_two is also changing even though I did not make any changes into it. I understand that both list_one and list_two refer to 'arr' but I was expecting list_one to create new reference to the modified list, and was expecting list_two to maintain existing reference to 'arr'.

please help me out.

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Puneet
  • 1

1 Answers1

0

The reason is that when you assign an array to list_one or list_two, you basically assigning the reference to the array, they are pointing to the same resource. So, since the two variables have the same reference to array, they do not only have equal values, but the values are the same as well.

You can also copy an array if needed, but assigning an array to a variable does not copy the whole array.

The docs also state it, like this:

Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other. This module provides generic shallow and deep copy operations (explained below).

Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175