Python Newbie: Creating an Empty Set

I have a code that picks up a set of selected values. I would like to define an empty set and add to it, but {} continues to turn into a dictionary. I found that if I populate a set with a dummy value, I can use it, but it's not very elegant. Can someone tell me the correct way to do this? Thank you

 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}

+14
source share
4 answers

You can just build a set:

 >>> s = set() 

will do the job.

+41
source

The "right" way to do this:

 myset = set() 

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

+5
source

As pointed out, the way to get the empy set literal is through set() , however, if you re-write your code, you don't need to worry about this, for example (and using set() ):

 from operator import itemgetter query = ['four', 'two', 'three'] result = set().union(*itemgetter(*query)(inversIndex)) # set([0, 1, 2]) 
+3
source

A collection literal is just a tuple of values ​​in braces:

 s = {2, 3, 5, 7} 

So, you can create an empty set with an empty tuple in braces:

 x = {()} 

However, just what you can does not mean you should.

If this is not a codegolf where each character matters, I would suggest explicit x = set() instead. "Explicit is better than implicit."

0
source

Source: https://habr.com/ru/post/1491510/


All Articles