

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Questions & Answers
- How to select only non - numeric values from varchar column in MySQL?
- How to set only numeric values for edittext in Android using Kotlin?
- MongoDB query to add timestamp only if it is not present
- List out the default values of numeric and non-numeric primitive data types in Java?
- How to check if a unicode string contains only numeric characters in Python?
- Array — Efficient arrays of numeric values in Python
- Fill missing numeric values in a JavaScript array
- Python Pandas - Display unique values present in each column
- How to select only numeric strings in MongoDB?
- How to add integer values to a C# list?
- How to add string values to a C# list?
- Python - Joining only adjacent words in list
- Program to count number of ways we can make a list of values by splitting numeric string in Python
- Add similar value multiple times in a Python list
- Get unique values from a list in Python
Advertisements