Python "in" set operator

I'm a little confused about python in operator for sets.

If I have a collection in Python s and some instance of b , is it true that b in s means "is there an element x in s such that b == x true "?

+102
python
Jan 02 2018-12-21T00:
source share
6 answers

Yes, but that also means hash(b) == hash(x) , so it's not enough to make them the same to distribute the elements evenly.

+76
Jan 02 2018-12-21T00:
source share

It is right. You can try it in the interpreter as follows:

 >>> a_set = set(['a', 'b', 'c']) >>> 'a' in a_set True >>>'d' in a_set False 
+55
Jan 02 2018-12-21T00:
source share

Yes, it could mean that, or it could be a simple iterator. For example: Example as an iterator:

 a=set(['1','2','3']) for x in a: print ('This set contains the value ' + x) 

Similar to checking:

 a=set('ILovePython') if 'I' in a: print ('There is an "I" in here') 

edited: edited to include sets, not lists and strings

+10
Jan 02 2018-12-12T00:
source share

Strings, although they are not set types, have a valuable in property during validation in scripts:

 yn = input("Are you sure you want to do this? ") if yn in "yes": #accepts 'y' OR 'e' OR 's' OR 'ye' OR 'es' OR 'yes' return True return False 

Hope this helps you better understand using in with this example.

+3
Jan 02 2018-12-12T00:
source share

Collections behave differently from dicts, you need to use operations such as issubset ():

 >>> k {'ip': '123.123.123.123', 'pw': 'test1234', 'port': 1234, 'debug': True} >>> set('ip,port,pw'.split(',')).issubset(set(k.keys())) True >>> set('ip,port,pw'.split(',')) in set(k.keys()) False 
+1
Jan 08 '19 at 8:23
source share

Yes. This means that the item is in the set.

0
Jan 02 2018-12-21T00:
source share



All Articles