Why is dictionary.keys() a list and not a set?

Christoph Zwerschke cito at online.de
Thu Nov 24 19:09:45 EST 2005


Martin v. Löwis schrieb:

 > Your original question was "could it be changed, and should it be
 > changed?" As the answer to the first part is already "no", the
 > second part really doesn't raise.

Right of course. The second part of the question was rather hypothetical 
(in the sense of "if we could start with Python from scratch, would it 
then be desirable").

 > In a set, all elements are different. In Python, this means that, for
 > any two elements X and Y of a set, X!=Y. Now, consider this set:
 > a = [1]
 > b = [1,2]
 > S = set(a,b)
 > a.append(2)
 > Now, a==b, so the inherent set property breaks. In theory, this should
 > cause S to contain only a single element; the other one should
 > disappear.

I just started to see these problems as well. I believed that the 
immutability of set elements had only technical reasons (hashing etc.) 
but your're right, it has also semantical reasons. In the above case, a 
or b would have to magically disappear, and even if that would be 
possible it would be completely unclear which of the two, and what would 
happen if you subsequently do a.append(3)? Should it magically appear 
again? So I understand you will get into very hot water if you try to 
implement sets with mutable elements.

 > This is not only hard to implement (removal from a set
 > would have to remove all duplicates, iterating over a set would have
 > to skip over duplicates) - there is also another semantical issue:
 > If one element is skipped/dropped, which of these (a or b)?

I should have read your posting fully before writing the above ;-)

-- Christoph



More information about the Python-list mailing list