Add only numeric values present in a list in Python

PythonServer Side ProgrammingProgramming

We have a Python list which contains both string and numbers. In this article we will see how to sum up the numbers present in such list by ignoring the strings.

With filter and isinstance

The isinstance function can be used to filter out only the numbers from the elements in the list. Then we apply and the sum function and get the final result.

Example

 Live Demo

listA = [1,14,'Mon','Tue',23,'Wed',14,-4]
#Given dlist
print("Given list: ",listA)
# Add the numeric values
res = sum(filter(lambda i: isinstance(i, int), listA))
print ("Sum of numbers in listA: ", res)

Output

Running the above code gives us the following result −

Given list: [1, 14, 'Mon', 'Tue', 23, 'Wed', 14, -4]
Sum of numbers in listA: 48

With for loop

It is a similar approach as a wall except that we don't use filter rather we use the follow and the is instance condition. Then apply the sum function.

Example

 Live Demo

listA = [1,14,'Mon','Tue',23,'Wed',14,-4]
#Given dlist
print("Given list: ",listA)
# Add the numeric values
res = sum([x for x in listA if isinstance(x, int)])
print ("Sum of numbers in listA: ", res)

Output

Running the above code gives us the following result −

Given list: [1, 14, 'Mon', 'Tue', 23, 'Wed', 14, -4]
Sum of numbers in listA: 48
raja
Published on 09-Jul-2020 12:38:30
Advertisements