Find Sum of Odd Elements from List in Python



In Python you can find the sum of all odd elements in an existing List one of the following ways -

  • Using List Comprehension

  • Using a Loop

  • Using filter() Function

Using List Comprehension

The List Comprehension method allows us to create a new list by applying an expression or condition to each element in list.

Example

Iterating over each Ithe element in the list (nums), filtering those elements using condition (if i % 2 == 1) to return only odd values and sum() function adds all the elements in the filtered list.

def solve(nums):
    return sum([i for i in nums if i % 2 == 1])

nums = [13,27,12,10,18,42]
print('The sum of odd elements is :',solve(nums))  

Output

The sum of odd elements is :  40

Using a Loop

One of the common approach to iterate over the list, to check each element if it's odd.

Example

In below example code initializing the sum as total = 0, iterating the each element using for loop and checks for odd elements using (if i % 2 == 1) and add those elements to total.

def solve(nums):
    total = 0
    for i in nums:
        if i % 2 == 1:
            total += i
    return total

nums = [5,7,6,4,6,9,3,6,2]
print('The sum of odd elements is :',solve(nums))  

Output

The sum of odd elements is:  24

Using filter() Function

This filter() is used to create an iterator that filters elements in existing list based on a given condition.

Example

In below example code to filter odd numbers in list filter(lambda x: x % 2 == 1, nums) function is used and passed the filtered list to sum() function.

def solve(nums):
    return sum(filter(lambda x: x % 2 == 1, nums))

nums = [5,7,6,4,6,3,6,2]
print('The sum of odd elements is :',solve(nums)) 

Output

The sum of odd elements is :  15
Updated on: 2024-10-04T15:40:27+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements