Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 04 Aug, 2022

Given a list that contains only string elements the task here is to write a Python program to check if all of them are numeric or not. If all are numeric return True otherwise, return False.

Input : test_list = ["434", "823", "98", "74"]
Output : True
Explanation : All Strings are digits.
Input : test_list = ["434", "82e", "98", "74"]
Output : False
Explanation : e is not digit, hence verdict is False.

Method 1 : Using all(), isdigit() and generator expression

In this, we check for numbers from isdigit(). all() is used to check for all strings to be number, and iteration for each string is done using generator expression.

Example:

Python3




# initializing list
test_list = ["434", "823", "98", "74"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# checking all elements to be numeric using isdigit()
res = all(ele.isdigit() for ele in test_list)
 
# printing result
print("Are all strings digits ? : " + str(res))


Output

The original list is : ['434', '823', '98', '74']
Are all strings digits ? : True

Time Complexity: O(n)

Space Complexity: O(n)

Method 2 : Using  all(), isdigit() and map()

In this, we extend test logic to each string using map(), rather than generator expression. Rest all the functionalities are performed similarly to the above method.

Example:

Python3




# initializing list
test_list = ["434", "823", "98", "74"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# checking all elements to be numeric using isdigit()
# map() to extend to each element
res = all(map(str.isdigit, test_list))
 
# printing result
print("Are all strings digits ? : " + str(res))


Output

The original list is : ['434', '823', '98', '74']
Are all strings digits ? : True

Time Complexity: O(n)

Auxiliary Space: O(n)

Method 3 : Using isnumeric() and len() methods

Python3




# initializing list
test_list = ["434", "82e", "98", "74"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# checking all elements to be numeric using isdigit()
c=0
for i in test_list:
    if i.isnumeric():
        c+=1
res=False
if(c==len(test_list)):
    res=True
 
# printing result
print("Are all strings digits ? : " + str(res))


Output

The original list is : ['434', '82e', '98', '74']
Are all strings digits ? : False

Time Complexity: O(n)

Space Complexity: O(n)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!