To sum only the numeric values in a list containing mixed data types, we iterate through the list, filter out non-numeric elements and then calculate the sum of the remaining numeric values.
Using filter and sum
One efficient to handle this is by combining the filter() function with the sum() function. filter() function selects only the numeric elements such as integers or floats based on a specified condition and the sum() function then calculates the total of these filtered values.
li = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
# sum to add only numeric values
res = sum(filter(lambda x: isinstance(x, int), li))
print(res)
Output
15
Explanation:
filter(lambda x: isinstance(x, int), li):Thisapplies a condition to each element of the listli.lambda x: isinstance(x, int):Thispart checks whether each elementxis of typeint.filter(): This returns a filtered iterator containing only the elements that satisfy the condition i.e. the integers from the list[1, 2, 3, 4, 5].sum():This takes the filtered iterator and calculates the sum of the elements. In this case, it adds the integers1 + 2 + 3 + 4 + 5, resulting in15.
Table of Content
Using list comprehension
list comprehension is a powerful way to create new lists by applying an expression to each element in an existing list. When combined with the sum() function, it provides an efficient method for filtering and summing only the numeric values from a list that contains mixed data types.
li = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
res = sum([x for x in li if isinstance(x, int)])
print(res)
Output
15
Explanation:
- list comprehension : This filters the list
lito include only integer values and the conditionisinstance(x, int)checks if each elementxis an integer. sum(): This function then adds the values in the filtered list .
Using for loop
for loop is a simple way to iterate through a list and sum numeric values. While easy to understand, it is less efficient than methods like filter() and list comprehension as it requires manually checking each element and summing conditionally.
li = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z']
# Manually summing numeric values using a loop
res = 0
for item in li:
if isinstance(item, int):
res += item
print(res)
Output
15
Explanation:
- For Loop: This iterates through each item in the list
li. isinstance(item, int):Thischecks if the currentitemis an integer.res += item:Thisadds the integer values toresin each iteration.