Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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
Truefor numeric strings,Falseotherwise - The
all()function returnsTrueonly if all elements returnTrue
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.
Advertisements
