liveBook · Manning

Membership operator

As explained in Python Workout, Second Edition

The in operator is Python's membership operator for testing whether a value occurs in a container or iterable.

Python’s in operator tests whether a value occurs in a sequence or collection. For example, if word[0] in 'aeiou' is True, the word begins with a vowel. This replaces repetitive loops and chained or conditions with a readable, Pythonic expression. section 3.3

if word[0] in 'aeiou':

Use membership testing directly when checking whether a character occurs in a string. section 3.3

Keep these behaviors in mind:

  • Apply in to strings, lists, tuples, and many other collections; searching takes time proportional to the sequence length. section 3.3
  • Search a dictionary with in to test keys, not values, then retrieve the associated value separately. section 3.3 section 5.5
  • Normalize user input when appropriate: capitalization affects dictionary-key matching, and casefold supports broader character handling. section 5.5

Restaurant menu

Check whether an order is a menu key before adding its price to a running total; reject unknown dishes, and stop when the stripped input is empty. section 5.4 section 5.5

How Python Workout, Second Edition covers it

How deep it goes
Explains syntax, supported containers, dictionary key behavior, search cost, and input-matching pitfalls without descending into implementation internals.
Examples
Demonstrates vowel detection and an interactive restaurant menu that accepts known dishes and rejects unknown ones.
What it assumes
Assumes basic Python strings, sequences, dictionaries, loops, and conditional expressions.
What you can do after
Apply the in operator to write concise sequence tests and safely check dictionary keys before retrieving values.
How it connects
Connects membership testing with strings, sequences, dictionaries, loops, Pig Latin, and case normalization.

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 Python Workout, Second Edition. The section links point to the parts of the book it draws on.