Skip to Content

Check If a Tuple Contains Only Numbers in Python

In this tutorial, we will look at how to check if a tuple contains only numbers in Python with the help of some examples.

check if tuple in python contains only numbers

You can use a combination of the Python built-in isinstance() and all() function to check if a tuple contains only numbers. For instance, you can use the following steps to check if all elements in a tuple are integers in Python –

  1. In a list comprehension, for each element in the tuple, check if it’s an integer using the isinstance() function.
  2. Apply the Python built-in all() function to return True only if all the items in the above list comprehension correspond to True.

The following is the code to check if all elements in a tuple are integers or not.

# check if all elements in tuple t are integers
all([isinstance(item, int) for item in t])

Let’s take a look at an example.

# tuple of numbers
t = (1, 2, 3, 4)
# check if tuple contains only numbers
print(all([isinstance(item, int) for item in t]))

Output:

Highlighted programs for you

Flatiron School

Flatiron School

Data Science Bootcamp
Product Design UX/UI Bootcamp

University of Maryland Global Campus

University of Maryland Global Campus

Cloud Computing Systems Master's
Digital Forensics & Cyber Investigation Master's

Creighton University

Creighton University

Health Informatics Master's

True

We get True as the output as all elements in the tuple t are integers.

Let’s take a look at another example.

# tuple of numbers and a string
t = (1, 2, 3, 4, 'cat')
# check if tuple contains only numbers
print(all([isinstance(item, int) for item in t]))

Output:

False

Here we get False as the output because not all elements in the tuple t are integers. One element, “cat” in the tuple is a string.

If you, however, have a tuple of strings and want to check whether all the elements in the tuple are digits or not, you can use the following code.

# tuple of numeric strings
t = ("1", "2", "3", "4")
# check if tuple of string contains only numberic elements
print(all([item.isdigit() for item in t]))

Output:

True

Here we check whether each element in the tuple of strings, t is a numerical string or not using the string isdigit() function. We get True as the output as all the strings in the tuple t are numeric characters.


You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.