Python’s in operator tests whether a value occurs in a collection and returns a Boolean. Use not in for the inverse test. section 5.5.1 section 8.11.2
Apply membership tests across common collection types:
- 3 in [1, 3, 4, 5] evaluates to True, while 3 in ["one", "two", "three"] evaluates to False. section 5.5.1
- Use in with lists, tuples, strings, and dictionaries to test membership in sequences or collections. section 8.11.2
- Sets also support in; converting a sequence with set removes duplicates before membership checks. section 5.8.1
- Strings are character sequences, so in can test whether a character occurs, although string methods are often simpler. section 6.4.7
Check before searching or removing
Use membership when existence is enough. If you need a list position, use index instead; calling index for a missing value raises ValueError. Testing first avoids that failure: if 7 in x: position = x.index(7). section 5.5.5 section 5.5.7
3 in [1, 3, 4, 5] True 3 not in [1, 3, 4, 5] False 3 in ["one", "two", "three"] False 3 not in ["one", "two", "three"] True
Compare positive and negative membership tests with numeric and string lists. section 5.5.1







