Python | Add only numeric values present in a list

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

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

 
Method #2: Using try and except



filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

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

 
Method #3: Using isinstance and conditional statements

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Programming freaktech Enthusiast and have interest in learning new upcoming technologies

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.