The Python Oracle

Python's "in" set operator

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Beneath the City Looping

--

Chapters
00:00 Python'S &Quot;In&Quot; Set Operator
00:18 Accepted Answer Score 128
00:37 Answer 2 Score 111
00:53 Answer 3 Score 15
01:19 Answer 4 Score 7
01:38 Answer 5 Score 3
01:56 Thank you

--

Full question
https://stackoverflow.com/questions/8705...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python

#avk47



ACCEPTED ANSWER

Score 128


Yes, but it also means hash(b) == hash(x), so equality of the items isn't enough to make them the same.




ANSWER 2

Score 112


That's right. You could try it in the interpreter like this:

>>> a_set = set(['a', 'b', 'c'])

>>> 'a' in a_set
True

>>>'d' in a_set
False



ANSWER 3

Score 15


Yes it can mean so, or it can be a simple iterator. For example: Example as iterator:

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

Similarly as a check:

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

edited: edited to include sets rather than lists and strings




ANSWER 4

Score 3


Strings, though 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

I hope this helps you better understand the use of in with this example.