Content · Programming · Python

Python operator.contains() Function: Usage and Examples

Test whether a collection contains a given item.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Test whether a collection contains a given item.

What You Will Learn


contains(container, item) performs item in container. Its argument order is container first, unlike the infix spelling item in container.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

from operator import contains
print(contains(['draft', 'ready'], 'ready'))
print(contains('notebook', 'book'))

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: operator.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

Expected output from the example:

True
True

When You Would Use This


These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.

Practice: Modify the Code


Check whether each user role is included in an allowed-role set.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Reversing arguments because the Python in expression places the item first.
  • Assuming the operation has the same behavior for missing values, empty inputs and regular inputs.

Key Takeaways


  • Test whether a collection contains a given item.
  • contains(container, item) performs item in container.
  • Apply this operation only after checking the assumptions and input conditions shown in the example.
Share this resourceSend this page to someone who may find it useful.