How to Check If a Set Contains Only Numbers in Python
Python sets are unordered collections of unique elements. Often, when processing data for mathematical operations (like union, intersection, or statistical analysis), you need to ensure that a set contains only numeric values (integers or floats) and no strings or other objects.
This guide explains how to validate the contents of a set using the all() function, isinstance(), and how to handle edge cases like empty sets.
Understanding Sets and Uniqueness
A set is defined using curly braces {} or the set() constructor. Its key characteristic is that it automatically removes duplicates.
# A mixed set containing numbers and a string
mixed_set = {1, 2.5, "apple", 4}
# A numeric set (duplicates removed)
numeric_set = {1, 2, 2, 3, 3.5}
print(f"Mixed: {mixed_set}")
print(f"Numeric: {numeric_set}")
Output:
Mixed: {'apple', 1, 2.5, 4}
Numeric: {3.5, 1, 2, 3}
Method 1: Using all() with isinstance() (Recommended)
To check if every element in the set is a number, we use the all() function. It takes an iterable and returns True only if every element evaluates to True.
We combine this with isinstance(x, (int, float)) to check types.
def is_set_numeric(data):
"""Returns True if all elements are int or float."""
return all(isinstance(x, (int, float)) for x in data)
set_a = {1, 2, 3}
set_b = {1, 2.5, "3"}
print(f"Set A is numeric? {is_set_numeric(set_a)}")
print(f"Set B is numeric? {is_set_numeric(set_b)}")
Output:
Set A is numeric? True
Set B is numeric? False
If you want to exclude Booleans (since bool is a subclass of int in Python), use:
isinstance(x, (int, float)) and not isinstance(x, bool)
Method 2: Handling Empty Sets
By definition, all() returns True for an empty iterable (this is called vacuous truth). Depending on your application logic, an empty set might be considered valid or invalid.
If you consider an empty set invalid (i.e., it doesn't contain numbers because it contains nothing), add an explicit check.
def is_set_numeric_strict(data):
# 1. Check if set is empty (False if empty)
if not data:
return False
# 2. Check types
return all(isinstance(x, (int, float)) for x in data)
empty_set = set()
print(f"Empty set (Standard): {all(isinstance(x, int) for x in empty_set)}")
print(f"Empty set (Strict): {is_set_numeric_strict(empty_set)}")
Output:
Empty set (Standard): True
Empty set (Strict): False
Conclusion
To verify if a set contains only numbers:
- Use
all(isinstance(x, (int, float)) for x in my_set)for a robust type check. - Decide on Empty Sets: If an empty set should fail validation, add
if not my_set: return Falsebefore the check.