594

[] = empty list

() = empty tuple

{} = empty dict

Is there a similar notation for an empty set? Or do I have to write set()?

martineau
  • 119,623
  • 25
  • 170
  • 301
Johan Råde
  • 20,480
  • 21
  • 73
  • 110
  • 25
    you don't accept {i for i in []}, didn't you? – utdemir May 25 '11 at 20:25
  • 3
    Just want to show nearly anything is possible with python. If you want to create a set without using to set(), you can. – utdemir May 25 '11 at 20:34
  • 7
    Yeah, you can do pretty much everything in a hundred convulted ways. I don't add `map(lambda x: x)` to my code examples just to show you it works either. It's not a set literal as well, it's just a set comprehension. –  May 25 '11 at 20:38
  • 2
    @utdemir [There should be one-- and preferably only one --obvious way to do it.](http://www.python.org/dev/peps/pep-0020/) – glglgl Jan 08 '14 at 11:35
  • 192
    A dumb way which works would be `{0}-{0}`. It's not as clear as `set()`, but it does have the advantage of looking like a funny pair of eyes. – wim Jan 27 '14 at 17:38
  • 1
    @wim How does that work? (I'm just curious, as I mistakenly used `{{}}` to denote an empty `dict(dict())`, and PyCharm mistook it for a set.) – Chris Sep 27 '15 at 13:55
  • 13
    @Chris `{}` is a dictionary. `{0}` is a set. `{0} - {0}` is the difference between a set and itself, which is the empty set. – michaelsnowden Oct 08 '15 at 02:52
  • 2
    I'm partial to `{*''}`, personally, if only because it resembles a face. (Don't use it seriously, though!) –  Jun 16 '18 at 02:48
  • 1
    @M.I.Wright For some reason, {*''} runs faster on my computer than set() – Kade Sep 26 '18 at 15:58
  • 4
    @Kade That sounds correct. Function calls are quite slow in Python (largely thanks to stack-manipulation overhead) so a call-less solution is always going to be faster -- cf. `f{a}'` vs `str(a)`. The issue with `{*''}` is simply that the speed gain isn't *really* worth temporarily confusing everybody who reads your code (and microoptimizations hardly ever matter in Python if you're not already using pypy). –  Sep 30 '18 at 13:37
  • 1
    Beware: while ``()`` is a tuple, ``('a string')`` is a string. In the latter, parenthesis just "protect" the content (letting you write expressions on multiple lines without a trailing ``\``). Initialize a tuple with one element by adding a comma: ``('a string', )`` is a tuple of length 1. – Q Caron Nov 19 '18 at 13:58
  • 3
    Many answers miss the fact that there is not way to make an empty set valid for `ast.literal_eval()`. `set()` does not work here. For everywhere else, I prefer dict() over {} and list() over []. Why not a PEP to suggest `{/}` as an empty set... or `{,}` – yota Sep 12 '19 at 07:11
  • this has been annoying me as well. empty set *should* be {}, to make it consistent with {0,1,3} being a set. empty dict should be {:}. – braaterAfrikaaner Dec 31 '22 at 16:37

7 Answers7

670

No, there's no literal syntax for the empty set. You have to write set().

phoenix
  • 7,988
  • 6
  • 39
  • 45
sepp2k
  • 363,768
  • 54
  • 674
  • 675
  • You mean there is no literal syntax for the empty set? Or for sets in general? – Johan Råde May 25 '11 at 20:23
  • 18
    There are set literals, but only in Python 3.x. There isn't a literal for empty sets either way. –  May 25 '11 at 20:27
  • 4
    @user763305: The language manual is pretty clear on this point. http://docs.python.org/library/stdtypes.html#set-types-set-frozenset says "non-empty sets ... can be created by placing a comma-separated list of elements within braces" – S.Lott May 25 '11 at 20:32
  • 47
    Actually, set literals have been backported to Python 2.7, so they are not only available strictly in Python 3. – Jim Brissom May 25 '11 at 20:56
  • 15
    @andy That's not an empty set - that's a set containing the number 1. You don't need the trailing comma by the way - that's only required for tuples. – sepp2k Jan 19 '15 at 13:12
95

By all means, please use set() to create an empty set.

But, if you want to impress people, tell them that you can create an empty set using literals and * with Python >= 3.5 (see PEP 448) by doing:

>>> s = {*()}  # or {*{}} or {*[]}
>>> print(s)
set()

this is basically a more condensed way of doing {_ for _ in ()}, but, don't do this.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
  • 1
    Why?! Performance is almost identical: `$ python3.7 -m timeit 'set()' 2000000 loops, best of 5: 177 nsec per loop $ python3.7 -m timeit '{*()}' 2000000 loops, best of 5: 171 nsec per loop` – ogurets Mar 31 '19 at 23:19
  • 39
    @ogurets, `set()` is likely much easier to understand (for code maintainers), and that often matters more than performance. `{*()}` seems "clever" in an almost pejorative sense. – benjimin Jun 07 '19 at 02:21
  • 2
    Heh, that's clever. – Ekrem Dinçel May 04 '20 at 20:51
  • 3
    If you want to _impress_ people, you say? – Dustin Oprea Jun 28 '21 at 02:27
  • Say you have a lot of non-empty sets in a file, and you suddenly have to write an empty one (say it's not implemented yet) then it may be better to declare a set this way for consistency. – LMCuber Sep 04 '21 at 20:56
51

Just to extend the accepted answer:

From version 2.7 and 3.1 python has got set literal {} in form of usage {1,2,3}, but {} itself still used for empty dict.

Python 2.7 (first line is invalid in Python <2.7)

>>> {1,2,3}.__class__
<type 'set'>
>>> {}.__class__
<type 'dict'>

Python 3.x

>>> {1,2,3}.__class__
<class 'set'>
>>> {}.__class__
<class 'dict'>

More here: https://docs.python.org/3/whatsnew/2.7.html#other-language-changes

Coder
  • 1,175
  • 1
  • 12
  • 32
Reishin
  • 1,854
  • 18
  • 21
  • 13
    This answer is wrong. There is still no literal syntax to represent an empty set. `{}.__class__` would still give `dict` – Ninja420 Mar 23 '16 at 18:56
  • 12
    @Ninja420 try to read first before comment, i have noticed that – Reishin Mar 24 '16 at 06:04
  • 5
    The accepted answer is still correct, and is not outdated. There is not a literal syntax for *the empty set*, there is however one for the empty dictionary. – AndreasHassing Jul 19 '16 at 08:34
  • 2
    @AndreasBjørn for an empty yes, however for non empty you will get PEP8 exception and suggestion to use set literal. – Reishin Jul 19 '16 at 19:47
  • 4
    actually, `{}.__class__` returns `'` with pyt3.6, not `` – Tsonglew Nov 19 '19 at 06:25
10

Yes. The same notation that works for non-empty dict/set works for empty ones.

Notice the difference between non-empty dict and set literals:

{1: 'a', 2: 'b', 3: 'c'} -- a number of key-value pairs inside makes a dict
{'aaa', 'bbb', 'ccc'} -- a tuple of values inside makes a set

So:

{} == zero number of key-value pairs == empty dict
{*()} == empty tuple of values == empty set

However the fact, that you can do it, doesn't mean you should. Unless you have some strong reasons, it's better to construct an empty set explicitly, like:

a = set()

Performance:

The literal is ~15% faster than the set-constructor (CPython-3.8, 2019 PC, Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz):

>>> %timeit ({*()} & {*()}) | {*()}
214 ns ± 1.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

>>> %timeit (set() & set()) | set()
252 ns ± 0.566 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

... and for completeness, Renato Garcia's frozenset proposal on the above expression is some 60% faster!

>>> ϕ = frozenset()

>>> %timeit (ϕ & ϕ) | ϕ
100 ns ± 0.51 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

NB: As ctrueden noticed in comments, {()} is not an empty set. It's a set with 1 element: empty tuple.

ankostis
  • 8,579
  • 3
  • 47
  • 61
pycoder
  • 477
  • 3
  • 10
  • 3
    `{()}` is not the empty set. It is a singleton set with one element: an empty tuple. You can verify this by checking `len({()})` which will be 1, or `() in {()}`, which will be `True`. – ctrueden Nov 08 '19 at 22:12
  • 2
    Oops, you're right! I updated the post: added the note about `{()}` not being an empty set, in case someone else makes the same mistake. Thank you, @ctrueden! – pycoder Nov 12 '19 at 05:26
6

It depends on if you want the literal for a comparison, or for assignment.

If you want to make an existing set empty, you can use the .clear() metod, especially if you want to avoid creating a new object. If you want to do a comparison, use set() or check if the length is 0.

example:

#create a new set    
a=set([1,2,3,'foo','bar'])
#or, using a literal:
a={1,2,3,'foo','bar'}

#create an empty set
a=set()
#or, use the clear method
a.clear()

#comparison to a new blank set
if a==set():
    #do something

#length-checking comparison
if len(a)==0:
    #do something
Brian Minton
  • 3,377
  • 3
  • 35
  • 41
  • 10
    `a=set()` does not *empty the set*, but creates a new set and assigns it to `a`, overwriting any previous value. – gerrit Feb 05 '14 at 11:55
  • Indeed. That's why I said that if you want to avoid creating a new object, you should use clear(). I suppose my comment should have been worded slightly differently. – Brian Minton Feb 05 '14 at 18:34
  • It also appears using the `a.clear()` method is slightly faster than `a=set()`, and checking `len(a)==0` is slightly faster than checking for equality to `a==set()` – Brian Minton Sep 08 '14 at 12:43
  • 4
    Instead of `if len(a)==0:` it suffices (and is more Pythonic) to write just `if a:` (edit: or rather, `if not a:` to match the polarity of the condition). – Jim Oldfield Nov 25 '15 at 11:57
4

Adding to the crazy ideas: with Python 3 accepting unicode identifiers, you could declare a variable ϕ = frozenset() (ϕ is U+03D5) and use it instead.

  • 4
    Problem is, `set` objects are mutable, so you're putting yourself at risk with `spam = ϕ; spam.add("eggs")`. – drdaeman Jun 15 '17 at 20:09
  • 4
    if `ϕ` is a frozenset, then `spam.add("eggs")` fails, because the frozenset object doesn't have any `add` method. – Brian Minton Dec 13 '17 at 14:46
  • 1
    @BrianMinton: But that is the intended behavior. Note that when someone writes `span = ϕ` both `span` and `ϕ` will point to the same object, i.e. `id(span) == id(ϕ)`. Hence, if `spam.add("eggs")` would work, the `ϕ` object would not be an empty set anymore, and we will come back to the original problem as pointed by drdaeman – Renato Garcia Feb 20 '18 at 19:36
  • 1
    @RenatoGarcia Compare with the empty dict literal: `>>> a={} >>> a['foo']='bar' >>> a {'foo': 'bar'} ` – Brian Minton Feb 21 '18 at 21:39
  • 4
    Why not use the "empty set" symbol (U+2205)`∅`, instead? – ankostis Sep 15 '20 at 08:30
-5

There are few ways to create empty Set in Python :

  1. Using set() method
    This is the built-in method in python that creates Empty set in that variable.
  2. Using clear() method (creative Engineer Technique LOL)
    See this Example:

    sets={"Hi","How","are","You","All"}
    type(sets)  (This Line Output : set)
    sets.clear()
    print(sets)  (This Line Output : {})
    type(sets)  (This Line Output : set)

So, This are 2 ways to create empty Set.

FBruzzesi
  • 6,385
  • 3
  • 15
  • 37
Meet Shah
  • 5
  • 1