The Wayback Machine - https://web.archive.org/web/20250220144952/https://www.geeksforgeeks.org/python-program-to-print-odd-numbers-in-a-list/
Open In App

Python program to print odd numbers in a List

Last Updated : 29 Nov, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

In this article, we will explore various methods to print odd numbers in a List. The simplest way to do this by using a Loop.

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.

Python
a = [10, 15, 23, 42, 37, 51, 62, 5]

# Using a for loop to print odd numbers
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.

Let’s explore other different method to find maximum of two numbers:

Using List Comprehension

List comprehension offers a more concise way to filter odd numbers from a list.

Python
a = [10, 15, 23, 42, 37, 51, 62, 5]

# List comprehension to filter odd numbers
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.

Python
a = [10, 15, 23, 42, 37, 51, 62, 5]

# Using filter() to get odd numbers
res = filter(lambda x: x % 2 != 0, a)

# Convert the filter object to a list and print
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.


Next Article

Similar Reads

three90RightbarBannerImg