![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements