I have some code which tots up a set of selected values. I would like to define an empty set and add to it, but {}
keeps turning into a dictionary. I have foun
A set literal is just a tuple of values in curly braces:
x = {2, 3, 5, 7}
So, you can create an empty set with empty tuple of values in curly braces:
x = {*()}
Still, just because you can, doesn't mean you should.
Unless it's an obfuscated programming, or a codegolf where every character matters, I'd suggest an explicit x = set()
instead.
"Explicit is better than implicit."
As has been pointed out - the way to get an empy set
literal is via set()
, however, if you re-wrote your code, you don't need to worry about this, eg (and using set()
):
from operator import itemgetter
query = ['four', 'two', 'three']
result = set().union(*itemgetter(*query)(inversIndex))
# set([0, 1, 2])
You can just construct a set:
>>> s = set()
will do the job.
The "proper" way to do it:
myset = set()
The {...}
notation cannot be used to initialize an empty set