peter.petrov
peter.petrov

Reputation: 39437

Python {} is not equal to set([]), why?

I am doing a few simple experiments with Python sets.
I noticed this strange (to me at least) behavior.

>>> {1,2,3} == set([1,2,3])
True
>>> {1} == set([1])
True
>>> {} == set([])
False

Why is the last result False?
I find it rather illogical.

Is there any good reason for this?

Upvotes: -1

Views: 504

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121486

{} creates an empty dictionary, not a set.

There is no empty set literal, just use set() (no arguments).

From the official Python tutorial on sets:

Curly braces or the set() function can be used to create sets. Note: to create an empty set you have to use set(), not {}; the latter creates an empty dictionary, a data structure that we discuss in the next section.

and from the set displays section of the expressions reference documentation:

An empty set cannot be constructed with {}; this literal constructs an empty dictionary.

Sets are a relatively late addition to the language; using {elem1, elem2} to create a set was only introduced in Python 3 and added to Python 2 in Python 2.7, but {} was used for empty dictionaries for, far, far longer, at least as early as 0.9.2 (released 1991).

Upvotes: 9

Related Questions