in | Python Keywords – Real Python

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:

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 comprehensions for data transformation

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

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