
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Add Only Numeric Values Present in a List in Python
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
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
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
Advertisements