Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

I've got a list that I create a copy of in order to do some manipulations while still keeping the original list. However, when I set copy_list equal to org_list, they become the same thing, and if I change copy_list, org_list changes too. For example:

org_list = ['y', 'c', 'gdp', 'cap']  copy_list = org_list  copy_list.append('hum')  print(copy_list) print(org_list) 

returns

['y', 'c', 'gdp', 'cap', 'hum'] ['y', 'c', 'gdp', 'cap', 'hum'] 

I don't know too much about what is actually going on but it looks like org_list is actually passing itself to copy_list so that they are actually the same thing.

Is there a way to make an independent copy of org_list without doing something clumsy like:

copy_list = [] for i in org_list:     copy_list.append(i) 

I say this because I have the same problem with other types of variables, for example a pandas dataframe.

like image 286
natsuki_2002 Avatar asked Nov 13 '13 10:11

natsuki_2002


People also ask

How do you copy a list without changing it in Python?

“Copying” a list just creates an alias for the same object in memory. To create a completely independent copy of a list, use the copy module's deepcopy() function.

How do you copy variables to another variable in Python?

In Python, we use = operator to create a copy of an object. You may think that this creates a new object; it doesn't. It only creates a new variable that shares the reference of the original object. Let's take an example where we create a list named old_list and pass an object reference to new_list using = operator.

What is the difference between deep copy and shallow copy in Python?

A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original. A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.


1 Answers

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[:]  
like image 68
yuvi Avatar answered Sep 28 '22 03:09

yuvi