Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

Python: why does my list change when I'm not actually changing it?

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.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason this is happening can be found here:

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

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

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

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

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

Finally, it is not a good idea to use list as an identifier as Python already uses this identifier for its own data structure (which is the reason I added the "m" in front of the variable names)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...