Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Confused with list.remove

Tags:

python

list

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!

like image 779
Sevik Avatar asked Mar 08 '12 17:03

Sevik


People also ask

How do I turn a list back into a string in Python?

To convert a list to a string, use Python List Comprehension and the join() function. The list comprehension will traverse the elements one by one, and the join() method will concatenate the list's elements into a new string and return it as output.

What is the difference between remove () and Del () in Python list?

The remove() function removes the first matching value from the list. The pop() function is used to return the removed element from the list. The del() function is used to delete an element at a specified index number in the list.

Can you remove items from lists in Python?

The remove() method is one of the ways you can remove elements from a list in Python. The remove() method removes an item from a list by its value and not by its index number.


1 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".

like image 94
Katriel Avatar answered Sep 19 '22 12:09

Katriel