简体   繁体   中英

Python: Confused with list.remove

I'm very new to Python, so sorry for the probably simple question. (Although, I spent now 2 hours to find an answer)

I simplified my code to illustrate the problem:

side=[5]
eva=side
print(str(side) + " side before")
print(str(eva) + " eva before")
eva.remove(5)
print(str(side) + " side after")
print(str(eva) + " eva after")

This yields:

[5] side before
[5] eva before
[] side after
[] eva after

Why does the remove command also affects the list 'side'? What can I do to use a copy of 'side', without modifying the list?

Thank you very much

Edit: Thank you very much for the good and comprehensible answers!

Python has "things" and "names for things". When you write

side = [5]

you make a new thing [5] , and give it the name side . When you then write

eva = side

you make a new name for side . Assignments are just giving names to things! There's still only one thing [5] , with two different names.

If you want a new thing, you need to ask for it explicitly. Usually you would do copy.copy(thing) , although in the case of lists there's special syntax thing[:] .

FYI "things" are usually called "objects"; "names" are usually called "references".

eva and side refer to the same list.

If you want to have a copy of the list:

eva = side[:]

You can read more about copying lists in this article: Python: copying a list the right way

Edit : That isn't the only way to copy lists. See the link posted in the first comment of this answer.

dusan's answer is correct, and is a clever approach, but I think it breaks the Zen of Python guideline that "Explicit is better than implicit."

A far more common pattern I've seen to ensure an item is a deepcopy is with the copy module.

>>> import copy
>>> eva = copy.copy(side)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM