Program to find sum of odd elements from list in Python


Suppose we have a list of n elements called nums. We have to find sum of all odd elements from the list.

So, if the input is like nums = [5,7,6,4,6,9,3,6,2], then the output will be 24 because 5+7+9+3 = 24.

To solve this, we will follow these steps −

  • Solve this by list comprehension also
  • l := a list of elements e for all e in nums and when e is odd
  • return the sum of elements in l by passing l into sum() function.

Example

Let us see the following implementation to get better understanding −

def solve(nums):
   return sum([i for i in nums if i % 2 == 1])
nums = [5,7,6,4,6,9,3,6,2]
print(solve(nums))

Input

[5,7,6,4,6,9,3,6,2]

Output

24

Updated on: 12-Oct-2021

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements