How to Check If a Number Is Within a List in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a number, or any item, exists within a list in Python. This is a fundamental operation for list manipulation and decision-making based on element presence.

This lab guides you through using the in operator to test for list membership, demonstrating its case-sensitive nature. You'll create a list of fruits and use the in operator to check for the presence of specific fruits, including those that are present, absent, and differ only in capitalization. You will also learn how to use the index() method to locate the position of an element within a list.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/ErrorandExceptionHandlingGroup(["Error and Exception Handling"]) python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/DataStructuresGroup -.-> python/lists("Lists") python/ErrorandExceptionHandlingGroup -.-> python/catching_exceptions("Catching Exceptions") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/conditional_statements -.-> lab-559554{{"How to Check If a Number Is Within a List in Python"}} python/lists -.-> lab-559554{{"How to Check If a Number Is Within a List in Python"}} python/catching_exceptions -.-> lab-559554{{"How to Check If a Number Is Within a List in Python"}} python/data_collections -.-> lab-559554{{"How to Check If a Number Is Within a List in Python"}} end

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.

Use the in Operator

In the previous step, you learned the basics of list membership and how to check if an item exists in a list using the in operator. In this step, we will explore more practical applications of the in operator, including using it within conditional statements to control the flow of your program.

The in operator is particularly useful in if statements. You can use it to execute certain blocks of code only when a specific item is present (or not present) in a list.

Let's continue with our fruits list example. Suppose you want to print a message only if "banana" is in the list. Create a file named in_operator.py in your ~/project directory:

## ~/project/in_operator.py
fruits = ["apple", "banana", "orange", "grape"]

if "banana" in fruits:
    print("Yes, banana is in the list")

Save the file and run it:

python ~/project/in_operator.py

You should see the following output:

Yes, banana is in the list

The if statement checks if "banana" is in the fruits list. If it is, the code inside the if block (the print statement) is executed.

Now, let's add an else block to handle the case where the item is not in the list:

Modify your in_operator.py file:

## ~/project/in_operator.py
fruits = ["apple", "banana", "orange", "grape"]

if "kiwi" in fruits:
    print("Yes, kiwi is in the list")
else:
    print("No, kiwi is not in the list")

Save the file and run it:

python ~/project/in_operator.py

You should see the following output:

No, kiwi is not in the list

Since "kiwi" is not in the fruits list, the code inside the else block is executed.

You can also use the not in operator in if statements. For example:

Modify your in_operator.py file:

## ~/project/in_operator.py
fruits = ["apple", "banana", "orange", "grape"]

if "kiwi" not in fruits:
    print("kiwi is not in the list")

Save the file and run it:

python ~/project/in_operator.py

The output will be:

kiwi is not in the list

This demonstrates how you can use the in and not in operators to create more complex logic in your Python programs. These operators are essential tools for working with lists and making decisions based on their contents.

Locate Position with index()

In the previous steps, you learned how to check if an item exists in a list using the in operator. Now, you'll learn how to find the position (index) of an item within a list using the index() method.

The index() method returns the index of the first occurrence of a specified value in a list. It's important to note that if the item is not found in the list, the index() method will raise a ValueError exception.

Let's continue with our fruits list example. Suppose you want to find the index of "banana" in the list. Create a file named index_method.py in your ~/project directory:

## ~/project/index_method.py
fruits = ["apple", "banana", "orange", "grape"]

index = fruits.index("banana")
print(index)

Save the file and run it:

python ~/project/index_method.py

You should see the following output:

1

This indicates that "banana" is located at index 1 in the fruits list. Remember that Python lists are zero-indexed, meaning the first element is at index 0, the second at index 1, and so on.

Now, let's try to find the index of an item that is not in the list, such as "kiwi":

Modify your index_method.py file:

## ~/project/index_method.py
fruits = ["apple", "banana", "orange", "grape"]

index = fruits.index("kiwi")
print(index)

Save the file and run it:

python ~/project/index_method.py

You should see an error message similar to this:

Traceback (most recent call last):
  File "/home/labex/project/index_method.py", line 3, in <module>
    index = fruits.index("kiwi")
ValueError: 'kiwi' is not in list

This ValueError indicates that "kiwi" is not found in the list.

To avoid this error, it's a good practice to first check if the item exists in the list using the in operator before using the index() method.

Here's how you can do it:

Modify your index_method.py file:

## ~/project/index_method.py
fruits = ["apple", "banana", "orange", "grape"]

if "kiwi" in fruits:
    index = fruits.index("kiwi")
    print(index)
else:
    print("kiwi is not in the list")

Save the file and run it:

python ~/project/index_method.py

You should see the following output:

kiwi is not in the list

This code first checks if "kiwi" is in the fruits list. If it is, it finds the index and prints it. Otherwise, it prints a message indicating that "kiwi" is not in the list, preventing the ValueError.

The index() method is a useful tool for finding the position of items in a list, but it's important to handle the case where the item might not be present to avoid errors.

Summary

In this lab, you learned how to check if an item exists within a list in Python using the in operator. The in operator returns True if the item is found in the list and False otherwise.

You also learned that the in operator is case-sensitive, meaning that "Apple" is different from "apple". The lab demonstrated these concepts with examples using a list of fruits and checking for the presence of specific items.