[]
= empty list
()
= empty tuple
{}
= empty dict
Is there a similar notation for an empty set
?
Or do I have to write set()
?
No, there's no literal syntax for the empty set. You have to write set()
.
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.
$ 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
set()
is likely much easier to understand (for code maintainers), and that often matters more than performance. {*()}
seems "clever" in an almost pejorative sense.
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
{}.__class__
would still give dict
{}.__class__
returns <class 'dict'>'
with pyt3.6, not <type 'dict'>
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.
{()}
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
.
{()}
not being an empty set, in case someone else makes the same mistake. Thank you, @ctrueden!
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
a=set()
does not empty the set, but creates a new set and assigns it to a
, overwriting any previous value.
a.clear()
method is slightly faster than a=set()
, and checking len(a)==0
is slightly faster than checking for equality to a==set()
Sep 8, 2014 at 12:43
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).
Nov 25, 2015 at 11:57
Adding to the crazy ideas: with Python 3 accepting unicode identifiers, you could declare a variable ϕ = frozenset()
(ϕ is U+03D5) and use it instead.
set
objects are mutable, so you're putting yourself at risk with spam = ϕ; spam.add("eggs")
.
ϕ
is a frozenset, then spam.add("eggs")
fails, because the frozenset object doesn't have any add
method.
Dec 13, 2017 at 14:46
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
Feb 20, 2018 at 19:36
>>> a={} >>> a['foo']='bar' >>> a {'foo': 'bar'}
Feb 21, 2018 at 21:39
There are few ways to create empty Set in Python :
So, This are 2 ways to create empty Set.
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.{0}-{0}
. It's not as clear asset()
, but it does have the advantage of looking like a funny pair of eyes.{}
is a dictionary.{0}
is a set.{0} - {0}
is the difference between a set and itself, which is the empty set.f{a}'
vsstr(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).