Newbie with a question, so please be gentle:
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 results in:
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 don’t understand why list is changing when I am only doing list2.remove(), not list.remove(). I’m not even sure what search terms to use to figure it out.
That’s because both
listandlist2are referring to the same list after you did the assignmentlist2=list.Try this to see if they are referring to the same objects or different:
An example:
If you really want to create a duplicate copy of
listsuch thatlist2doesn’t refer to the original list but a copy of the list, use the slice operator:An example:
Also, don’t use
listas a variable name, because originally,listrefers to the type list, but by defining your ownlistvariable, you are hiding the originallistthat refers to the type list. Example: