There were no set literals in Python 2, historically curly braces were only used for dictionaries. Sets could be produced from lists (or any iterables):
set([1, 2, 3])
set([i for i in range(1, 3)])
To create an empty set, use
my_set = set()
Python 3 introduced set literals and comprehensions (see PEP-3100) which allowed us to avoid intermediate lists:
{1, 2, 3}
{i for i in range(1, 3)}
The empty set form, however, was reserved for dictionaries due to backwards compatibility. References from [Python-3000] sets in P3K? states:
I'm sure we can work something out --- I agree, {}
for empty set and {:}
for empty dict would be ideal, were it not for backward compatibility. I
liked the "special empty object" idea when I first wrote the PEP (i.e.,
have {}
be something that could turn into either a set or dict), but one
of the instructors here convinced me that it would just lead to confusion
in newcomers' minds (as well as being a pain to implement).
The following message describes these rules better:
I think Guido had the best solution. Use set()
for empty sets, use {}
for empty dicts, use {genexp}
for set comprehensions/displays, use
{1,2,3}
for explicit set literals, and use {k1:v1, k2:v2}
for dict
literals. We can always add {
/}
later if demand exceeds distaste.
set
is like adict
with keys but no values, and they're both implemented using a hash table. But yes, it's a little annoying that the{}
notation denotes an emptydict
rather than an emptyset
, but that's a historical artifact. I've seen a suggestion that{:}
should be an emptydict
and{}
an emptyset
, but I doubt that'll ever be implemented, as it clashes with too much existing code. – Montoya{}
is an emptydict
because Python has always haddict
s, since they're fundamental to the way Python works: normal object attributes are stored in adict
, and variables behave as if they are name:value pairs in adict
(although they aren't necessarily implemented that way for efficiency reasons). Whereasset
s were added to the language quite a while later. (Of course, before then it was always possible to "fake" a set by using adict
with dummy values). – Montoya