Python Program to check whether all elements in a string list are numeric

When working with string lists, you often need to check whether all elements contain only numeric characters. Python provides the all() function combined with isdigit() method to accomplish this task efficiently.

Using all() and isdigit()

The all() function returns True if all elements in an iterable are true, and isdigit() checks if a string contains only digits ?

my_list = ["434", "823", "98", "74", "9870"]

print("The list is:")
print(my_list)

my_result = all(ele.isdigit() for ele in my_list)

if my_result:
    print("All the elements in the list are numeric")
else:
    print("All the elements in the list are not numeric")
The list is:
['434', '823', '98', '74', '9870']
All the elements in the list are numeric

Testing with Mixed Content

Here's an example with non-numeric elements to see how the function behaves ?

mixed_list = ["123", "abc", "456", "78"]

print("The mixed list is:")
print(mixed_list)

result = all(ele.isdigit() for ele in mixed_list)

if result:
    print("All elements are numeric")
else:
    print("Not all elements are numeric")
The mixed list is:
['123', 'abc', '456', '78']
Not all elements are numeric

How It Works

The solution uses a generator expression (ele.isdigit() for ele in my_list) that:

  • Iterates through each string element in the list
  • Applies isdigit() to check if the string contains only digits
  • Returns True for numeric strings, False otherwise
  • The all() function returns True only if all elements return True

Conclusion

Use all() with isdigit() to efficiently check if all elements in a string list are numeric. This approach is concise and readable for validation tasks.

Updated on: 2026-03-26T02:19:18+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements