Keywords and Expressions
in — Membership and iteration syntax
As a comparison, test membership in a container. Dictionaries test keys, strings test substrings, and sequences search for matching elements. Custom types can implement __contains__; otherwise Python can use iteration or the legacy integer-index protocol. Searching an iterator may consume items, including the matching one. not in negates membership. In a for header or comprehension, in separates the target from its iterable; that syntax is not a membership test.
Formal Syntax & Structure
python syntaxpython
item in containeritem not in container
for target in iterable: suiteParameters & Attributes
| Name | Type | Description |
|---|---|---|
| item | object | Value to search for in the comparison form. |
| container | container or iterable | Object providing membership semantics. |
Return Value
bool (comparison form)
Whether membership holds; the for-header form is not an expression.
Working Example
Example Snippetpython
prices = {"pen": 2, "book": 7}print("pen" in prices)print(7 in prices)print("py" in "python")iterator = iter([1, 2, 3])print(2 in iterator, list(iterator))