Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Add only numeric values present in a list in Python
We have a Python list which contains both strings and numbers. In this article we will see how to sum up the numbers present in such list by ignoring the strings.
Using filter() and isinstance()
The isinstance() function can be used to filter out only the numbers from the elements in the list. Then we apply the sum() function to get the final result.
Example
mixed_data = [1, 14, 'Mon', 'Tue', 23, 'Wed', 14, -4]
# Given list
print("Given list:", mixed_data)
# Add the numeric values using filter
result = sum(filter(lambda i: isinstance(i, int), mixed_data))
print("Sum of numbers in mixed_data:", result)
The output of the above code is −
Given list: [1, 14, 'Mon', 'Tue', 23, 'Wed', 14, -4] Sum of numbers in mixed_data: 48
Using List Comprehension
This approach uses list comprehension with the isinstance() condition to filter numeric values, then applies the sum() function ?
Example
mixed_data = [1, 14, 'Mon', 'Tue', 23, 'Wed', 14, -4]
# Given list
print("Given list:", mixed_data)
# Add the numeric values using list comprehension
result = sum([x for x in mixed_data if isinstance(x, int)])
print("Sum of numbers in mixed_data:", result)
The output of the above code is −
Given list: [1, 14, 'Mon', 'Tue', 23, 'Wed', 14, -4] Sum of numbers in mixed_data: 48
Using try-except Block
Another approach is to use exception handling to catch non-numeric values and skip them ?
Example
mixed_data = [1, 14, 'Mon', 'Tue', 23, 'Wed', 14, -4]
# Given list
print("Given list:", mixed_data)
# Add the numeric values using try-except
total = 0
for item in mixed_data:
try:
total += item
except TypeError:
pass # Skip non-numeric values
print("Sum of numbers in mixed_data:", total)
The output of the above code is −
Given list: [1, 14, 'Mon', 'Tue', 23, 'Wed', 14, -4] Sum of numbers in mixed_data: 48
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
filter() |
Medium | Good | Functional programming style |
| List Comprehension | High | Best | Most Python code |
| try-except | Medium | Slower | Mixed data types |
Conclusion
List comprehension with isinstance() is the most Pythonic approach for summing numeric values in mixed lists. Use filter() for functional programming style or try-except when dealing with complex data types.
