Difference between del and remove?

T

Terry Reedy

| Got a quick n00b question. What's the difference between del and
| remove?

Python has a del statement but not a remove statement. Correspondingly,
the first is a keyword and the second is not.

tjr
 
S

Steven D'Aprano

Got a quick n00b question. What's the difference between del and remove?

Everything. list.remove(value) removes the first item equal to value.
del list[index] removes the item at position index.

See also: help([].remove)


Help on built-in function remove:

remove(...)
L.remove(value) -- remove first occurrence of value


alist = [101, 102, 103, 104, 105]
alist.remove(103)
alist [101, 102, 104, 105]
del alist[0]
alist
[102, 104, 105]
 
T

Tim Roberts

Yansky said:
Got a quick n00b question. What's the difference between del and
remove?

It would have been easier to answer if you had given a little context.

"del" is a Python statement that removes a name from a namespace, an item
from a dictionary, or an item from a list.

"remove" is a member function of the 'list' class that finds a specific
entry in the list and removes it.

Example:
[9, 8, 6]
e = [9,8,7,6] ; e.remove(2) ; e
Traceback (most recent call last):
e = [9,8,7,6] ; e.remove(8) ; e
[9, 7, 6]

Note that "del e[2]" removed item number 2 (counting from 0). e.remove(8)
removed the item that had the value 8 from the list. e.remove(2) failed
because the number 2 was not in the list.

Dictionaries do not have a "remove" method. You have to use the "del"
statement.
 
Y

Yansky

Thanks for the clarification guys. :)

Yansky said:
Got a quick n00b question. What's the difference between del and
remove?

It would have been easier to answer if you had given a little context.

"del" is a Python statement that removes a name from a namespace, an item
from a dictionary, or an item from a list.

"remove" is a member function of the 'list' class that finds a specific
entry in the list and removes it.

Example:
e = [9,8,7,6] ; del e[2] ; e

[9, 8, 6]
e = [9,8,7,6] ; e.remove(2) ; e

Traceback (most recent call last):
e = [9,8,7,6] ; e.remove(8) ; e

[9, 7, 6]

Note that "del e[2]" removed item number 2 (counting from 0). e.remove(8)
removed the item that had the value 8 from the list. e.remove(2) failed
because the number 2 was not in the list.

Dictionaries do not have a "remove" method. You have to use the "del"
statement.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top