Python: why does my list change when I don't change it?

Beginner with a question, so please be careful:

list = [1, 2, 3, 4, 5] list2 = list def fxn(list,list2): for number in list: print(number) print(list) list2.remove(number) print("after remove list is ", list, " and list 2 is ", list2) return list, list2 list, list2 = fxn(list, list2) print("after fxn list is ", list) print("after fxn list2 is ", list2) 

This leads to:

 1 [1, 2, 3, 4, 5] after remove list is [2, 3, 4, 5] and list 2 is [2, 3, 4, 5] 3 [2, 3, 4, 5] after remove list is [2, 4, 5] and list 2 is [2, 4, 5] 5 [2, 4, 5] after remove list is [2, 4] and list 2 is [2, 4] after fxn list is [2, 4] after fxn list2 is [2, 4] 

I do not understand why the list changes when I only do list2.remove() and not list.remove() . I'm not even sure what search terms to use to figure this out.

+4
source share
2 answers

This is because both list and list2 belong to the same list after completing the list2=list job.

Try this to see if they apply to the same objects or to others:

 id(list) id(list2) 

Example:

 >>> list = [1, 2, 3, 4, 5] >>> list2 = list >>> id(list) 140496700844944 >>> id(list2) 140496700844944 >>> list.remove(3) >>> list [1, 2, 4, 5] >>> list2 [1, 2, 4, 5] 

If you really want to create a duplicate copy of list so that list2 does not refer to the original list but to the copy of the list, use the slice operator:

 list2 = list[:] 

Example:

 >>> list [1, 2, 4, 5] >>> list2 [1, 2, 4, 5] >>> list = [1, 2, 3, 4, 5] >>> list2 = list[:] >>> id(list) 140496701034792 >>> id(list2) 140496701034864 >>> list.remove(3) >>> list [1, 2, 4, 5] >>> list2 [1, 2, 3, 4, 5] 

Also, do not use list as the name of the variable, because initially the list refers to a list of types, but by defining your own variable list , you hide the original list that refers to the list of types. Example:

 >>> list <type 'list'> >>> type(list) <type 'type'> >>> list = [1, 2, 3, 4, 5] >>> list [1, 2, 3, 4, 5] >>> type(list) <type 'list'> 
+5
source

The reason this is happening can be found here:

 mlist = [1,2,3,4,5] mlist2 = mlist 

the second operator "points" mlist2 to mlist (that is, they both refer to the same list object), and any changes you make in one are reflected in the other.

To make a copy, try this (using the slice operation):

 mlist = [1,2,3,4,5] mlist2 = mlist[:] 

In case you are curious about fragment notation, this SO <Python Lists (Slice method) question will give you more background.

Finally, it is not recommended to use list as an identifier, since Python already uses this identifier for its own data structure (for this reason I added " m " before the variable names)

+14
source

All Articles