liveBook · Manning

Membership operator

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

A membership expression tests whether a value occurs in a collection or other container.

The membership operator uses `x in y` to test whether value `x` occurs in collection `y`, returning `True` or `False`. Python applies the same form to strings, lists, and dictionary keys. section 2.5 section 4.1.2

Use membership tests to make small programs safer and clearer:

  • Check a character against a string of vowels before choosing an article: `word[0].lower() in 'aeiou'`. section 2.3.3
  • Check whether a list contains an item before acting on it; unlike `list.index()`, membership returns `False` instead of raising an exception for an absent item. section 3.3.5
  • Check whether a dictionary contains a key before retrieving its value, avoiding a missing-key `KeyError`. section 4.1.2

Testing membership in different collections

>>> word = 'oracle' >>> word[0].lower() in 'aeiou' True >>> items = ['sandwiches', 'plates', 'chips'] >>> 'chips' in items True >>> 'fog machine' in items False >>> answers = {'quest': 'To seek the Holy Grail'} >>> 'quest' in answers True >>> 'age' in answers False section 2.3.3 section 3.3.5 section 4.1.2

>>> word[0]
'o'

Inspect the indexed character that becomes the left-hand value of a membership test. section 2.3.3

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Defines Boolean presence tests across strings, lists, and dictionaries, but does not detail implementation internals or performance.
Examples
Demonstrates vowel checks, picnic-item checks, dictionary-key checks, and letter matching in a command-line lookup program.
What it assumes
Assumes basic Python expressions, indexing, strings, lists, dictionaries, and conditional logic.
What you can do after
Apply it via Python expressions to test presence before branching, retrieving values, or reporting unknown input.
How it connects
Connects strings, lists, dictionaries, indexing, conditional expressions, and safe dictionary or list lookup.

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 Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.