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
forloops to traverse Python iterables - Writing comprehensions for data transformation
For additional information on related topics, take a look at the following resources:
- Python for Loops: The Pythonic Way (Tutorial)
- When to Use a List Comprehension in Python (Tutorial)
- Python Dictionary Comprehensions: How and When to Use Them (Tutorial)
- Python Set Comprehensions: How and When to Use Them (Tutorial)
- Checking for Membership Using Python's "in" and "not in" Operators (Course)
- For Loops in Python (Definite Iteration) (Course)
- Python for Loops: The Pythonic Way (Quiz)
- Understanding Python List Comprehensions (Course)
- When to Use a List Comprehension in Python (Quiz)
- Building Dictionary Comprehensions in Python (Course)
- Python Dictionary Comprehensions: How and When to Use Them (Quiz)
- Python Set Comprehensions: How and When to Use Them (Quiz)