in

In Python, the in keyword is used for membership tests, for loops, comprehensions, and generator expressions. In all cases, its syntax involves a value and an iterable, value in iterable.

Python in Keyword Examples

Here’s a quick example to demonstrate how you can use the in keyword:

Python
>>> # Membership tests
>>> fruits = ["apple", "banana", "cherry"]
>>> "banana" in fruits
True
>>> "orange" in fruits
False

>>> # Loop
>>> for fruit in fruits:
...     print(fruit)
...
apple
banana
cherry

>>> # Comprehenshion
>>> squares = [number**2 for number in [1, 2, 3]]
>>> squares
[1, 4, 9]

In this example, you use the in keyword to check whether "banana" is in the fruits list and get True. Similarly, you check for "orange," which isn’t in the list, and get False.

Next, you use in as part of a for loop that iterates over your list of fruits. Finally, you use in to create a list comprehension that builds a list of square values.

Python in Keyword Use Cases

  • Running membership tests to check for the existence of an element in an iterable
  • Implementing for loops to traverse Python iterables
  • Writing comprehension for data transformation

Tutorial

Python's "in" and "not in" Operators: Check for Membership

In this tutorial, you'll learn how to check if a given value is present or absent in a collection of values using Python's in and not in operators, respectively. This type of check is known as membership test in Python.

basics best-practices python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Jan. 6, 2025 • Reviewed by Dan Bader