26

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}

user5305519
  • 3,008
  • 4
  • 26
  • 44
Chris Degnen
  • 8,443
  • 2
  • 23
  • 40

4 Answers4

62

You can just construct a set:

>>> s = set()

will do the job.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
Jon Kiparsky
  • 7,499
  • 2
  • 23
  • 38
8

The "proper" way to do it:

myset = set()

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

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
3

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])
Jon Clements
  • 138,671
  • 33
  • 247
  • 280
3

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

pycoder
  • 477
  • 3
  • 10