How to Check If a List Contains Only Numbers in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a list contains only numbers in Python. This involves defining numeric lists, including lists of integers, floating-point numbers, and mixed numbers. You will create a Python file named numeric_lists.py and use the VS Code editor to define and print these lists to the console.

The lab guides you through defining lists of integers, floats, and a mix of both, demonstrating how to create and print these lists using Python. You'll use the print() function to display the contents of each list, ensuring you understand how to work with numeric lists in Python.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/ControlFlowGroup(["Control Flow"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/BasicConceptsGroup -.-> python/numeric_types("Numeric Types") python/ControlFlowGroup -.-> python/conditional_statements("Conditional Statements") python/DataStructuresGroup -.-> python/lists("Lists") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/PythonStandardLibraryGroup -.-> python/data_collections("Data Collections") subgraph Lab Skills python/numeric_types -.-> lab-559527{{"How to Check If a List Contains Only Numbers in Python"}} python/conditional_statements -.-> lab-559527{{"How to Check If a List Contains Only Numbers in Python"}} python/lists -.-> lab-559527{{"How to Check If a List Contains Only Numbers in Python"}} python/build_in_functions -.-> lab-559527{{"How to Check If a List Contains Only Numbers in Python"}} python/data_collections -.-> lab-559527{{"How to Check If a List Contains Only Numbers in Python"}} end

Define Numeric Lists

In this step, you will learn how to define numeric lists in Python. A list is a collection of items, and in this case, we'll focus on lists containing numbers. Lists are a fundamental data structure in Python and are used to store and manipulate ordered sequences of data.

First, let's create a new Python file named numeric_lists.py in your ~/project directory using the VS Code editor.

~/project/numeric_lists.py

Now, open numeric_lists.py in the editor and add the following code to define a list of integers:

## Define a list of integers
integer_list = [1, 2, 3, 4, 5]

## Print the list to the console
print(integer_list)

Save the file. Next, open a terminal in VS Code and navigate to the ~/project directory. You should already be in this directory by default. Now, execute the Python script using the following command:

python numeric_lists.py

You should see the following output:

[1, 2, 3, 4, 5]

Now, let's define a list of floating-point numbers (decimal numbers):

Modify the numeric_lists.py file to include the following:

## Define a list of floating-point numbers
float_list = [1.0, 2.5, 3.7, 4.2, 5.9]

## Print the list to the console
print(float_list)

Save the file and run the script again:

python numeric_lists.py

You should see the following output:

[1.0, 2.5, 3.7, 4.2, 5.9]

You can also create a list containing a mix of integers and floating-point numbers:

Modify the numeric_lists.py file to include the following:

## Define a list of mixed numbers (integers and floats)
mixed_list = [1, 2.0, 3, 4.5, 5]

## Print the list to the console
print(mixed_list)

Save the file and run the script again:

python numeric_lists.py

You should see the following output:

[1, 2.0, 3, 4.5, 5]

Congratulations! You have successfully defined and printed numeric lists in Python. This is a fundamental step towards working with numerical data in Python.

Use all() with isinstance()

In this step, you will learn how to use the all() function in combination with the isinstance() function to check if all elements in a list are of a specific numeric type. This is a useful technique for validating data and ensuring that your code behaves as expected.

The all() function returns True if all elements in an iterable (like a list) are true. The isinstance() function checks if an object is an instance of a specified class or type.

Let's modify the numeric_lists.py file you created in the previous step to include the following code:

def check_if_all_numeric(data):
  """
  Check if all elements in the list are either integers or floats.
  """
  return all(isinstance(item, (int, float)) for item in data)

## Test cases
integer_list = [1, 2, 3, 4, 5]
float_list = [1.0, 2.5, 3.7, 4.2, 5.9]
mixed_list = [1, 2.0, 3, 4.5, 5]
string_list = [1, 2, "hello", 4.5, 5]

print(f"Integer list is all numeric: {check_if_all_numeric(integer_list)}")
print(f"Float list is all numeric: {check_if_all_numeric(float_list)}")
print(f"Mixed list is all numeric: {check_if_all_numeric(mixed_list)}")
print(f"String list is all numeric: {check_if_all_numeric(string_list)}")

Here's a breakdown of the code:

  • We define a function check_if_all_numeric(data) that takes a list as input.
  • Inside the function, we use all() with a generator expression (isinstance(item, (int, float)) for item in data).
  • The generator expression iterates through each item in the data list and checks if it's an instance of either int or float using isinstance().
  • all() returns True only if all items in the list are either integers or floats; otherwise, it returns False.
  • We then test the function with different lists and print the results.

Save the numeric_lists.py file and run it from the terminal:

python numeric_lists.py

You should see the following output:

Integer list is all numeric: True
Float list is all numeric: True
Mixed list is all numeric: True
String list is all numeric: False

This output shows that the check_if_all_numeric() function correctly identifies whether all elements in a list are numeric. The string list contains a string, so the function returns False.

Handle Empty Lists

In this step, you will learn how to handle empty lists when using the all() and isinstance() functions. An empty list is a list that contains no elements. It's important to handle empty lists correctly to avoid unexpected behavior in your code.

Let's modify the numeric_lists.py file you created in the previous steps to include a check for empty lists in the check_if_all_numeric() function:

def check_if_all_numeric(data):
  """
  Check if all elements in the list are either integers or floats.
  Handle empty lists gracefully.
  """
  if not data:
    return True  ## An empty list can be considered as all numeric

  return all(isinstance(item, (int, float)) for item in data)

## Test cases
integer_list = [1, 2, 3, 4, 5]
float_list = [1.0, 2.5, 3.7, 4.2, 5.9]
mixed_list = [1, 2.0, 3, 4.5, 5]
string_list = [1, 2, "hello", 4.5, 5]
empty_list = []

print(f"Integer list is all numeric: {check_if_all_numeric(integer_list)}")
print(f"Float list is all numeric: {check_if_all_numeric(float_list)}")
print(f"Mixed list is all numeric: {check_if_all_numeric(mixed_list)}")
print(f"String list is all numeric: {check_if_all_numeric(string_list)}")
print(f"Empty list is all numeric: {check_if_all_numeric(empty_list)}")

Here's what we've changed:

  • We added a check at the beginning of the check_if_all_numeric() function: if not data:. This checks if the list is empty.
  • If the list is empty, we return True. This is because an empty list can be considered as satisfying the condition that all its elements are numeric (since it has no elements that are not numeric).
  • We added an empty_list test case.

Save the numeric_lists.py file and run it from the terminal:

python numeric_lists.py

You should see the following output:

Integer list is all numeric: True
Float list is all numeric: True
Mixed list is all numeric: True
String list is all numeric: False
Empty list is all numeric: True

As you can see, the check_if_all_numeric() function now correctly handles empty lists and returns True for them. This makes your code more robust and less prone to errors when dealing with potentially empty lists.

Summary

In this lab, the initial step focuses on defining numeric lists in Python, covering lists of integers, floating-point numbers, and mixed numeric types. The process involves creating a Python file, numeric_lists.py, and populating it with list definitions using square brackets and comma-separated values. The print() function is then used to display these lists to the console, demonstrating how to create and output various numeric lists.

The lab emphasizes the fundamental data structure of lists in Python and their ability to store ordered sequences of numeric data. By defining and printing different types of numeric lists, including integers, floats, and a combination of both, the lab provides a practical introduction to working with numeric data within Python lists.