Skip to content
Related Articles

Related Articles

Python | Add only numeric values present in a list

View Discussion
Improve Article
Save Article
  • Last Updated : 30 Jun, 2022
View Discussion
Improve Article
Save Article

Given a list containing characters and numbers, the task is to add only numbers from a list. Given below are a few methods to complete a given task. 
Method #1: Using filter() and lambda 

Python3




# Python code to demonstrate
# how to add only numbers present
# in a list of characters and numbers
 
# initialising lists
ini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
 
# printing initial list
print ("initial list", str(ini_list))
 
# code to add numbers from list
res = sum(filter(lambda i: isinstance(i, int), ini_list))
 
# printing result
print ("resultant sum", res)

Output:

initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
resultant sum 15

  Method #2: Using try and except 

Python3




# Python code to demonstrate
# how to add only numbers present
# in a list of characters and numbers
 
# initialising lists
ini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
 
# printing initial list
print ("initial list", str(ini_list))
 
# code to add numbers from list
res = 0
for item in ini_list:
    try:
        res+= int(item)
    except ValueError:
        pass
 
# printing result
print ("resultant sum", res)

Output:

initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
resultant sum 15

  Method #3: Using isinstance and conditional statements 

Python3




# Python code to demonstrate
# how to add only numbers present
# in a list of characters and numbers
 
# initialising lists
ini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
 
# printing initial list
print ("initial list", str(ini_list))
 
# code to add numbers from list
res = sum([x for x in ini_list if isinstance(x, int)])
 
# printing result
print ("resultant sum", res)

Output:

initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
resultant sum 15

Method #4: Using type() and find() methods

Python3




# Python code to demonstrate
# how to add only numbers present
# in a list of characters and numbers
 
# initialising lists
ini_list = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
 
# printing initial list
print ("initial list", str(ini_list))
 
# code to add numbers from list
res=0
for i in ini_list:
    p=str(type(i))
    if(p.find('int')!=-1):
        res+=int(i)
# printing result
print ("resultant sum", res)
 
#contributed by Bhavya Koganti

Output

initial list [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
resultant sum 15

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!