Add only Numeric Values Present in a List Python (original) (raw)
Last Updated : 17 Jan, 2025
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.
Python `
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)
`
**Explanation:
filter(lambda x: isinstance(x, int), li):
This
applies a condition to each element of the list_**li
**_.lambda x: isinstance(x, int):
This
part checks whether each elementx
is of typeint
.- **filter() : Thisreturns 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 integers
1 + 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.
Python `
li = [1, 2, 3, 4, 'a', 'b', 'x', 5, 'z'] res = sum([x for x in li if isinstance(x, int)]) print(res)
`
**Explanation:
- *list comprehension : This filters the list _*
li
_ to include only integer values and the conditionisinstance(x, int)
checks if each element _x
**_ is 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.
Python `
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)
`
**Explanation:
- *For Loop: This iterates through each item in the list _*
li
**_. isinstance(item, int):
This
checks if the currentitem
is an integer.res += item:
This
adds the integer values to_**res
**_ in each iteration.
Similar Reads
- Counting number of unique values in a Python list Counting the number of unique values in a Python list involves determining how many distinct elements are present disregarding duplicates. Using a SetUsing a set to count the number of unique values in a Python list leverages the property of sets where each element is stored only once. [GFGTABS] Pyt 2 min read
- Print all Strong Numbers in Given List - Python The task of printing all Strong numbers from a given list in Python involves iterating through the list and checking each number based on its digit factorial sum. A Strong number is a number whose sum of the factorials of its digits equals the number itself. For example, given a list a = [145, 375, 4 min read
- Python - Add Values to Dictionary of List A dictionary of lists allows storing grouped values under specific keys. For example, in a = {'x': [10, 20]}, the key 'x' maps to the list [10, 20]. To add values like 30 to this list, we use efficient methods to update the dictionary dynamically. Let’s look at some commonly used methods to efficien 3 min read
- Python | Add similar value multiple times in list Adding a single value in list is quite generic and easy. But to add that value more than one time, generally, a loop is used to execute this task. Having shorter tricks to perform this can be handy. Let's discuss certain ways in which this can be done. Method #1 : Using * operator We can employ * op 5 min read
- Python | Assign value to unique number in list We can assign all the numbers in a list a unique value that upon repetition it retains that value retained to it. This is a very common problem that is faced in web development when playing with id's. Let's discuss certain ways in which this problem can be solved. Method #1: Using enumerate() + list 7 min read
- Python Program to Count Even and Odd Numbers in a List In Python working with lists is a common task and one of the frequent operations is counting how many even and odd numbers are present in a given list. The collections.Counter method is the most efficient for large datasets, followed by the filter() and lambda approach for clean and compact code. Us 4 min read
- Python program to print positive numbers in a list In this article, we will explore various methods to o print positive numbers in a list. The simplest way to do is by using for loop function. Using LoopThe most basic method for printing positive numbers is to use a for loop to iterate through the list and check each element. [GFGTABS] Python a = [- 2 min read
- Sum of number digits in List in Python Our goal is to calculate the sum of digits for each number in a list in Python. This can be done by iterating through each number, converting it to a string, and summing its digits individually. We can achieve this using Python’s built-in functions like sum(), map(), and list comprehensions. For exa 2 min read
- Make a Set of Lists in Python Creating a set of lists typically involves defining multiple lists and organizing them into a structure, such as a dictionary or another list. In this article, we will see how we can make a set of lists in Python. Table of Content Creating a Set of List Using list() FunctionMake A Set Of Lists Using 3 min read
- Python - Ways to find indices of value in list In Python, it is common to locate the index of a particular value in a list. The built-in index() method can find the first occurrence of a value. However, there are scenarios where multiple occurrences of the value exist and we need to retrieve all the indices. Python offers various methods to achi 3 min read