Reputation: 1591
I know python list has a remove() method, which remove the given object from the list.
aList = [123, 'xyz', 'zara', 'abc', 'xyz']
aList.remove('xyz')
I know that we can use del statement to delete an item from the list by offset:
del aList[-1]
I also know that we can use del statement to delete an item from the dictionary by key:
aDict = {'a':1, 'b':2 'c':3}
del aDict['a']
However, there is no remove() method for a dictionary, which I think is perfectly fine:
aDict.remove('a')
I guess one reason is that remove() does not save any typing than del statement for dictionary, so it is not necessary. Is this correct?
While for list, remove() combines "search index by value" and "delete by index" together, so it has to be there. Is this correct?
What are the other reasons if any?
Upvotes: 4
Views: 1312
Reputation: 134046
Dictionaries have pop
, but not remove
. Why not? Because remove
finds the first matching value and removes it, and returns nothing. So in a dictionary:
{'a': 5, 'b': 5}
dict.remove
ought to remove values. If I use dict.remove(5)
, which key should it delete? Additionally this is not even very useful operation. If you need to remove a certain value from a dictionary, then you're using a wrong data structure.
dct.pop(key)
on the other hand, is not unlike
value = dct[key]
del dct[key]
return value
This can be contrasted with pop
method of lists:
lst.pop(index)
is analogous to
value = lst[index]
del lst[index]
return value
that is, both of them operate using the same principle.
Upvotes: 1
Reputation: 52099
Note that list.remove
makes a very strict guarantee - removing the first occurrence of a value. Now, the ordering in a dict
is arbitrary - there is no "first".
Upvotes: 4
Reputation: 1311
If you look at this question: Difference between del, remove and pop on lists : you'll note the main answer points out
remove: removes the first matching value, not a specific index
del: removes a specific index
pop: returns the removed element
So with a Dictionary it simply doesn't need a remove method as there can only be one instance of a key (they have to be unique) and del
is sufficient.
Upvotes: 4