del and sets proposal

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sun Oct 5 10:15:41 EDT 2008


Steven D'Aprano a écrit :
> On Sat, 04 Oct 2008 18:36:28 +0200, Bruno Desthuilliers wrote:
> 
>>> Yes I know that sets have a remove method (like lists), but since
>>> dictionaries don't have a remove method, shouldn't sets behave like
>>> more like dictionaries and less like lists?  IMHO del for sets is quite
>>> intuitive.
>> For lists, del a[x] means 'remove item at index x'. For dicts, del a[x]
>> means 'remove key:value pair which key is x'. In both cases, del a[x] is
>> meaningful because a[x] is meaningful. Sets are neither ordered nor
>> indexed, and can't be subscripted. So "del aset[x]" is IMHO as
>> meaningless as 'aset[x]' is. Using this syntax for an operation which
>> semantic is the same as alist.remove(x) would be at best inconsistent
>> and confusing.
> 
> Consider the mutable built-in collections set, dict and list, and how 
> they remove elements:
> 
> aset.remove(x)
> alist.remove(x)
> del adict[x]

This last one doesn't remove the key,value pair(s) where *the value* is 
x, it removes the key,value pair where the *key* is x - which is 
semantically very different, just like alist.remove(x) is very different 
from del alist[x].

> Would it really be "confusing" if sets used the same interface as dicts 
> use? I don't think so.

I do. In both dict.__delitem__ and list.__delitem__, the argument is an 
index (whether arbitrary key or positional index), not the value of the 
element to remove. wrt/ consistency, i'd rather have dict growing a 
remove(value) method with same semantic as list.remove and set.remove 
than abuse subscript syntax to duplicate an existing API which has a 
very different semantic.

> What else could "del aset[x]" mean

As far as I'm concerned, since sets are not subscriptables, del aset[x] 
just can't have any meaning.

> other than 
> "delete element x"?

Going this way, 'del adict[x]' should mean 'remove key,value pair(s) 
where value is x' and 'del alist[x]' should be an alias for alist.remove(x).


> Lists are the odd one out, because del alist[x] is used to remove the 
> element at position x, rather than removing an element x.

Nope. It's perfectly consistent with dicts, where del adict[x] is used 
to remove element associated to key x, not to remove element with value 
x. Lists and dicts are both indexed collections, list being indexed by 
position and dicts by key. sets are not indexed.

(snip remaining - I could only keep on repeating the same thing).



More information about the Python-list mailing list