Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find sum of odd elements from list in Python
In Python, you can find the sum of all odd elements in an existing List using 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 the list.
Example
This approach iterates over each element in the list, filters odd elements using the condition i % 2 == 1, and uses the sum() function to add all filtered elements ?
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))
The sum of odd elements is: 40
Using a Loop
This is a common approach that iterates over the list to check each element if it's odd.
Example
Initialize the sum as total = 0, iterate through each element using a for loop, check for odd elements using 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))
The sum of odd elements is: 24
Using filter() Function
The filter() function creates an iterator that filters elements in an existing list based on a given condition.
Example
Use filter(lambda x: x % 2 == 1, nums) to filter odd numbers and pass the filtered result to the 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))
The sum of odd elements is: 15
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| List Comprehension | High | Fast | Concise filtering operations |
| Loop | High | Good | Complex logic or beginners |
| filter() Function | Medium | Memory efficient | Functional programming style |
Conclusion
List comprehension provides the most concise and readable solution for finding the sum of odd elements. Use loops for more complex logic or when learning Python fundamentals.
