liveBook · Manning

Membership operator

As explained in The Quick Python Book, Fourth Edition

The in operator is a Python comparison operator that tests whether a value is contained in a collection.

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

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Defines Boolean membership and contrasts existence checks with index-based position lookup, without discussing implementation internals.
Examples
Uses numeric and string lists, sets with duplicate removal, character strings, and guarded list searches.
What it assumes
Assumes familiarity with Python collections, Boolean expressions, and basic list operations.
What you can do after
Apply it to check collection membership and guard index or removal operations against missing values.
How it connects
Connects membership with lists, tuples, sets, strings, dictionaries, Boolean operators, and the index method.

Also explained in

Compare how 8 books explain membership operator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.