The Python Oracle

Empty set literal?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Peaceful Mind

--

Chapters
00:00 Question
00:26 Accepted answer (Score 656)
00:40 Answer 2 (Score 91)
01:16 Answer 3 (Score 51)
01:59 Answer 4 (Score 10)
03:28 Thank you

--

Full question
https://stackoverflow.com/questions/6130...

Accepted answer links:
[set()]: https://docs.python.org/3/library/stdtyp...

Answer 2 links:
[see PEP 448]: https://www.python.org/dev/peps/pep-0448/

Answer 3 links:
https://docs.python.org/3/whatsnew/2.7.h...

Answer 4 links:
[frozenset]: https://stackoverflow.com/a/44576113/548...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #set #literals

#avk47



ACCEPTED ANSWER

Score 707


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




ANSWER 2

Score 103


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.




ANSWER 3

Score 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




ANSWER 4

Score 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