The Python Oracle

Python's "in" set operator

This video explains
Python's "in" set operator

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Bleepage Open

--

Chapters
00:00 Question
00:27 Accepted answer (Score 122)
00:43 Answer 2 (Score 106)
00:58 Answer 3 (Score 13)
01:26 Answer 4 (Score 7)
01:45 Thank you

--

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

Accepted answer links:
[hash(b) == hash(x)]: http://docs.python.org/reference/datamod...

--

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

--

Tags
#python



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.