Print odd numbers in a List – Python
We are given a list and our task is to print all the odd numbers from it. This can be done using different methods like a simple loop, list comprehension, or the filter() function. For example, if the input is [1, 2, 3, 4, 5], the output will be [1, 3, 5].
Using Loop
The most basic way to print odd numbers in a list is to use a for loop with if conditional check to identify odd numbers.
a = [10, 15, 23, 42, 37, 51, 62, 5]
for i in a:
if i % 2 != 0:
print(i)
Output
15 23 37 51 5
Explanation:
- Loops through list a.
- For each element i, checks if i % 2 != 0 (i.e., if the number is odd).
- If the condition is true then print the odd number.
Using List Comprehension
List comprehension is similar to the for loop method shown above but offers a more concise way to filter odd numbers from a list.
a = [10, 15, 23, 42, 37, 51, 62, 5]
res = [i for i in a if i % 2 != 0]
print(res)
Output
[15, 23, 37, 51, 5]
Explanation: This list comprehension filters all elements in a where i % 2 != 0 (i.e., the number is odd).
Using filter() Function
The filter() function can also be used to filter out odd numbers. The filter() function applies a function to each item in the iterable and returns a filter object containing only those items where the function returns True.
a = [10, 15, 23, 42, 37, 51, 62, 5]
res = filter(lambda x: x % 2 != 0, a)
print(list(res))
Output
[15, 23, 37, 51, 5]
Explanation:
- filter() function takes two arguments: a lambda function (lambda x: x % 2 != 0) that checks if the number is odd and the iterable ‘a’.
- The result is a filter object which we convert to a list and print.
Related Articles: