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:
>>> # 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
forloops to traverse Python iterables - Writing comprehensions for data transformation
Related Resources
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.
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)