0

I want to manipulate a List in python while keeping the original List untouched.
So I've substituted the Original List into a new defined variable as below :

Original_List = [1,5]
Substituted_List = Orginal_List

But I've noticed doing Substituted_List.append() also modify the Original_List too:

Substituted_List.append(3)
print("Original list is: %s" %Original_List)
print("Substituted list is: %s" %Substituted_List)  

The output is:

Original list is: [1,5,3]
Substituted list is: [1,5,3]

While the Original list is supposed to be: [1,5]

Mohsen Haddadi
  • 1,296
  • 2
  • 16
  • 20

3 Answers3

2

It is because you are referencing the same object:

>>> Original_List = [1,5]
>>> Substituted_List = Original_List
>>> 
>>> id(Original_List)
140473860198344
>>> id(Substituted_List)
140473860198344
>>>

you need to use:

Substituted_List = Original_List[:]

or you can use:

import copy
Substituted_List = copy.copy(Original_List)
JkShaw
  • 1,927
  • 2
  • 13
  • 14
1

This is because you are copying the reference

Substituted_List = Original_List

To make a copy instead use a slice operation :

Substituted_List = Original_List[:]
akash karothiya
  • 5,736
  • 1
  • 19
  • 29
0

The concept is that in Python each and every variable is an object which points to your data in memory. When a list is substituted to another variable(object), then the other variable also references to the old memory point which the original variable has pointed to. If you do not want that the substituted list-variable gets changed then use list() function. ex:-

>>> list1 = [1,2,3]
>>> list2 = list(list1)
>>> print(list1, list2)
[1, 2, 3] [1, 2, 3]
>>> list1[2]=4
>>> print(list1, list2)
[1, 2, 4] [1, 2, 3]
A. Agarwal
  • 11
  • 3