Open In App

Python - Sum Elements Matching Condition

Last Updated : 10 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are having a list we need to find sum of list with matching condition ( here given matching condition is number should be even ). For example, n = [1, 2, 3, 4, 5, 6] so that output should be 12.

Using List Comprehension with sum()

Using list comprehension with sum() allows us to efficiently sum elements that meet a specific condition in a single line. The comprehension filters elements based on a condition and sum() aggregates only matching values.

Python
n = [1, 2, 3, 4, 5, 6]
# Sum of even numbers
res = sum(x for x in n if x % 2 == 0)  
print(res) 

Output
12

Explanation:

  • Generator expression x for x in n if x % 2 == 0 filters even numbers from the list n selecting only elements divisible by 2.
  • sum() function then adds up these selected even numbers (2 + 4 + 6 = 12) and prints result.

Using filter() with sum()

Using filter() with sum() allows us to sum elements that satisfy a given condition by first filtering them filter() function extracts matching elements and sum() computes their total efficiently.

Python
n = [1, 2, 3, 4, 5, 6]
# Sum of even numbers from the list
res = sum(filter(lambda x: x % 2 == 0, n))  
print(res)  

Output
12

Explanation:

  • Filter(lambda x: x % 2 == 0, numbers) extracts only even numbers from the numbers list using a lambda function.
  • Sum() function then adds up these filtered even numbers and stores the result in res which is printed.

Using a for Loop

Using a for loop we can iterate through list and check each element against a condition. If element meets condition we add it to a running sum accumulating total.

Python
n = [1, 2, 3, 4, 5, 6] 
res = 0 
for num in n:  
     # Check if the number is even
    if num % 2 == 0: 
        # Add even number to the sum
        res += num  

print(res)  

Output
12

Explanation:

  • for loop iterates through each element in list n checking if it's even using num % 2 == 0.
  • If number is even it is added to res accumulating sum which is then printed.

Next Article
Practice Tags :

Similar Reads