Why is dictionary.keys() a list and not a set?
"Martin v. Löwis"
martin at v.loewis.de
Thu Nov 24 23:24:00 CET 2005
Christoph Zwerschke wrote:
> I know. But this does not answer the question: If the keys *are* already
> a set according to their semantics, why aren't they returned as a set
> from the beginning?
Notice that this was not the question you originally asked. This
one has a clear answer: because that was always the case, and because
it was never changed.
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.
> This, of course, in turn raises the question ;-) Would it be desirable
> to have an additional, more general set datatype that can contain
> mutable objects? I know about the perfomance drawbacks. And I think I
> know the answer: It would not make much sense, since the implementation
> would be actually not different from a list. So you could take a list
> anyway. Which gives the answer why values() and items() return a list.
Actually, this answer is only partial. The real question is a semantical
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 = 
b = [1,2]
S = set(a,b)
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. 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)?
More information about the Python-list