Chris Degnen
Chris Degnen

Reputation: 8655

Creating an empty set

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 found if I populate the set with a dummy value I can use it, but it's not very elegant. Can someone tell me the proper way to do this? Thanks.

inversIndex = {'five': {1}, 'ten': {2}, 'twenty': {3},
               'two': {0, 1, 2}, 'eight': {2}, 'four': {1},
               'six': {1}, 'seven': {1}, 'three': {0, 2},
               'nine': {2}, 'twelve': {2}, 'zero': {0, 1, 3},
               'eleven': {2}, 'one': {0}}

query = ['four', 'two', 'three']

def orSearch(inverseIndex, query):
    b = [ inverseIndex[c] for c in query ]
    x = {'dummy'}
    for y in b:
        { x.add(z) for z in y }
    x.remove('dummy')
    return x

orSearch(inverseIndex, query)

{0, 1, 2}

Upvotes: 29

Views: 53244

Answers (4)

pycoder
pycoder

Reputation: 547

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."

Upvotes: 4

inspectorG4dget
inspectorG4dget

Reputation: 114035

The "proper" way to do it:

myset = set()

The {...} notation cannot be used to initialize an empty set

Upvotes: 10

Jon Clements
Jon Clements

Reputation: 142216

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])

Upvotes: 3

Jon Kiparsky
Jon Kiparsky

Reputation: 7753

You can just construct a set:

>>> s = set()

will do the job.

Upvotes: 64

Related Questions