Skip to content

How to Check If a List Contains a Number in Python

Learn how to detect numeric values (integers or floats) in a Python list containing mixed data types using isinstance() and any() for efficient boolean checks.

Mixed-type lists in Python can store integers, strings, booleans, and floats simultaneously. When processing such data, a common requirement is to determine if the list contains any numeric values before performing mathematical operations.

This guide explains how to identify numeric elements within a mixed list using the isinstance() function and the any() built-in.

Understanding Mixed-Type Lists

A mixed-type list is a sequence that holds elements of different data types. Because Python is dynamically typed, a single list can contain text, numbers, and logical values.

my_list = [1, "hello", 3.14, True]

print(f"List content: {my_list}")
print(f"Type of first element: {type(my_list[0])}")   # <class 'int'>
print(f"Type of second element: {type(my_list[1])}")  # <class 'str'>

Output:

List content: [1, 'hello', 3.14, True]
Type of first element: <class 'int'>
Type of second element: <class 'str'>

Method 1: Using any() with isinstance() (Boolean Check)

The most efficient way to check if a list contains at least one number is to combine the any() function with a generator expression.

  • isinstance(x, (int, float)): Checks if x is either an integer or a float.
  • any(...): Returns True if at least one element in the iterable satisfies the condition.
data = ["apple", "banana", "cherry", 42, "date"]


has_number = any(isinstance(x, (int, float)) and not isinstance(x, bool) for x in data)

print(f"List contains a number: {has_number}")

Output:

List contains a number: True

Method 2: Extracting Numeric Elements (Filtering)

If you need to retrieve the actual numbers rather than just checking for their existence, use a list comprehension or a loop.

mixed_data = [1, "hello", 3.14, True, 5, "world"]

numeric_values = [
    x for x in mixed_data 
    if isinstance(x, (int, float)) and not isinstance(x, bool)
]

print(f"Original: {mixed_data}")
print(f"Numbers found: {numeric_values}")
print(f"Sum of numbers: {sum(numeric_values)}")

Output:

Original: [1, 'hello', 3.14, True, 5, 'world']
Numbers found: [1, 3.14, 5]
Sum of numbers: 9.14

Conclusion

To handle numeric checks in mixed lists:

  1. Use isinstance(x, (int, float)) to identify numbers.
  2. Combine with any() for a quick boolean check.
  3. Use List Comprehensions to extract or filter the numeric data for processing.
Navigation