python: changes to my copy variable affect the original variable [duplicate]

Solution 1:

That is because in python setting a variable actually sets a reference to the variable. Almost every person learning python encounters this at some point. The solution is simply to copy the list:

copy_list = org_list[:] 

Solution 2:

When you write

org_list = ['y', 'c', 'gdp', 'cap']

you create the list object, and give it the name "org_list".

Then when you do

copy_list = org_list

you just mean, "the name copy_list refers to the same object as org_list does".

If your list only contains immutable types, then you can create a copy by

copy_list = list(org_list)

But note that this is only valid if the list objects are immutable, because it creates a SHALLOW copy, i.e. the list is copied, but every element on the list is not duplicated.

If you have i.e. a list of lists and want EVERYTHING to be duplicated, you need to perform a DEEP copy:

import copy
org_list = ['y', 'c', ['gdp', 'rtd'], 'cap']
copy_list = copy.deepcopy(org_list)