Understand List Membership
In this step, you will learn how to check if an item exists within a list in Python. This is a fundamental operation when working with lists and is often used to make decisions based on the presence or absence of specific elements.
Python provides a convenient operator called in
to test for membership. The in
operator returns True
if the item is found in the list, and False
otherwise.
Let's start by creating a list of fruits:
fruits = ["apple", "banana", "orange", "grape"]
Now, let's use the in
operator to check if "apple"
is in the fruits
list. Create a file named membership.py
in your ~/project
directory using the VS Code editor:
## ~/project/membership.py
fruits = ["apple", "banana", "orange", "grape"]
print("apple" in fruits)
Save the file and run it using the following command in the terminal:
python ~/project/membership.py
You should see the following output:
True
This indicates that "apple"
is indeed a member of the fruits
list.
Now, let's check for an item that is not in the list, such as "kiwi"
:
Modify your membership.py
file to check for "kiwi"
:
## ~/project/membership.py
fruits = ["apple", "banana", "orange", "grape"]
print("kiwi" in fruits)
Save the file and run it again:
python ~/project/membership.py
You should see the following output:
False
This confirms that "kiwi"
is not a member of the fruits
list.
The in
operator is case-sensitive. This means that "Apple"
is different from "apple"
. Let's demonstrate this:
Modify your membership.py
file:
## ~/project/membership.py
fruits = ["apple", "banana", "orange", "grape"]
print("Apple" in fruits)
Save the file and run it:
python ~/project/membership.py
You should see:
False
Even though "apple"
is in the list, "Apple"
(with a capital "A") is not.
You can also use the not in
operator to check if an item is not in a list. For example:
Modify your membership.py
file:
## ~/project/membership.py
fruits = ["apple", "banana", "orange", "grape"]
print("kiwi" not in fruits)
Save the file and run it:
python ~/project/membership.py
The output will be:
True
This is because "kiwi"
is not in the fruits
list.
Understanding list membership is crucial for writing conditional statements and controlling the flow of your Python programs.