Python: why does my list change when I'm not actually changing it? -
newbie question, please gentle:
list = [1, 2, 3, 4, 5] list2 = list def fxn(list,list2): number in list: print(number) print(list) list2.remove(number) print("after remove list ", list, " , list 2 ", list2) return list, list2 list, list2 = fxn(list, list2) print("after fxn list ", list) print("after fxn list2 ", list2)
this results in:
1 [1, 2, 3, 4, 5] after remove list [2, 3, 4, 5] , list 2 [2, 3, 4, 5] 3 [2, 3, 4, 5] after remove list [2, 4, 5] , list 2 [2, 4, 5] 5 [2, 4, 5] after remove list [2, 4] , list 2 [2, 4] after fxn list [2, 4] after fxn list2 [2, 4]
i don't understand why list changing when doing list2.remove()
, not list.remove()
. i'm not sure search terms use figure out.
that's because both list
, list2
referring same list after did assignment list2=list
.
try see if referring same objects or different:
id(list) id(list2)
an 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 want create duplicate copy of list
such list2
doesn't refer original list copy of list, use slice operator:
list2 = list[:]
an 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, don't use list
variable name, because originally, list
refers type list, defining own list
variable, hiding original list
refers type list. example:
>>> list <type 'list'> >>> type(list) <type 'type'> >>> list = [1, 2, 3, 4, 5] >>> list [1, 2, 3, 4, 5] >>> type(list) <type 'list'>
Comments
Post a Comment