183

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

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

2
  • 23
    Computer Scientist. I'm just a little confused because the documentation says "Test x for membership in s." To me that could mean "the instance x is contained in s" or "some instance exists in s that has the same value as x". I don't know whether this is an identity or equality comparison.
    – Dejas
    Jan 2, 2012 at 21:18
  • 8
    @Dejas: Since you're aware that Python has two operators Equality comparison and identity comparison, you should be able to construct an experiment that confirms each. It would help if you posted that experiment.
    – S.Lott
    Jan 2, 2012 at 21:40

6 Answers 6

125

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

3
  • 18
    Ok so "is there an element x in s such that hash(b) == hash(x) and x == b"?
    – Dejas
    Jan 2, 2012 at 21:25
  • 14
    If someone implemented his class's hash function in a twisted way, this is what he may get (and deserve).
    – ugoren
    Jan 2, 2012 at 21:52
  • 4
    I think the documentation on membership testing should state more clearly that hash equality is a precondition for set, frozenset and dict. An improvement like that was discussed in a bug report in 2015, but unfortunately it got closed in 2019: bugs.python.org/issue23987#msg241661. Nov 18, 2020 at 10:16
107

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
1
  • 2
    This is not a very good test since string constants are often interned (try a = 'a'; b = 'a'; a is b). I tried it with a = (1, 2, 3); b = (1, 2, 3); a == b; hash(a) == hash(b); a is b; a in set([b]) instead.
    – Philipp
    Jan 2, 2012 at 21:35
13

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

3
  • 3
    What does this have to do with sets? Jan 2, 2012 at 23:19
  • well I suppose a list or even a string can be considered to have similar properties to a set. They are a collection of elements. Jan 3, 2012 at 7:08
  • 2
    No, sets have an additional condition for a containment check that sequences do not. Jan 3, 2012 at 7:09
7

Sets behave different than dicts, you need to use set operations like 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
3
  • That's interesting. And a great real-world application as well. Apr 5, 2019 at 15:33
  • 1
    This is precisely the surprising result that brought me here. Nov 30, 2020 at 21:41
  • why surprising? the in operator tests for element membership, and that holds for sets, dicts, lists, tuples and so on. The second test is (naively) testing if the set is a an element of the keys set. And no, it is not: the set of keys contains only keys, not sets
    – MestreLion
    Oct 16, 2021 at 18:47
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.

2
  • 3
    That's not a set. Nor are strings mutable. Jan 2, 2012 at 23:19
  • 8
    ... or 'e' or 'es' or 's'. Consider just deleting this pointlessly wrong answer. Jul 23, 2014 at 22:48
2

List's __contains__ method uses the __eq__ method of its elements. Whereas set's __contains__ uses __hash__. Have a look to the following example that I wish will be explicit:

class Salary:
    """An employee receives one salary for each job he has."""

    def __init__(self, value, job, employee):
        self.value = value
        self.job = job
        self.employee = employee

    def __repr__(self):
        return f"{self.employee} works as {self.job} and earns {self.value}"

    def __eq__(self, other):
        """A salary is equal to another if value is equal."""
        return self.value == other.value

    def __hash__(self):
        """A salary can be identified with the couple employee-job."""
        return hash(self.employee) + hash(self.job)

alice = 'Alice'
bob = 'Bob'
engineer = 'engineer'
teacher = 'teacher'

alice_engineer = Salary(10, engineer, alice)
alice_teacher = Salary(8, teacher, alice)
bob_engineer = Salary(10, engineer, bob)

print(alice_engineer == alice_teacher)
print(alice_engineer == bob_engineer, '\n')

print(alice_engineer is alice_engineer)
print(alice_engineer is alice_teacher)
print(alice_engineer is bob_engineer, '\n')

alice_jobs = set([alice_engineer, alice_teacher])
print(alice_jobs)
print(bob_engineer in alice_jobs)  # IMPORTANT
print(bob_engineer in list(alice_jobs))  # IMPORTANT

Console prints:

False
True 

True
False
False 

{Alice works as teacher and earns 8, Alice works as engineer and earns 10}
False
True

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.