Extract Odd numbers from a List in Python

In this article, we will discuss different ways to select odd numbers from a list in Python.

Table Of Contents

Introduction

Suppose we have a list, that contains only numbers. Like this,

[10, 11, 11, 23, 14, 36, 12, 20, 18, 171, 78, 91, 9, 10]

We want to fetch only odd numbers from this list. Like this,

[11, 11, 23, 171, 91, 9]

There are different ways to do this. Let’s discuss them one by one.

Method 1: Using List Comprehension

To fetch odd numbers from a list, iterate over all numbers of the list using List comprehension, and select only odd numbers. This selection can be done by using an if condition inside the List comprehension. To check if a given number is odd or not, divide it by 2, if the reminder is 1, then it means that the given number is odd. Let’s see an example,

# List of Numbers
listOfNumbers = [10, 11, 11, 23, 14, 36, 12, 20, 18, 171, 78, 91, 9, 10]

# Select only odd numbers from a list in Python
oddNumbers = [elem for elem in listOfNumbers if elem % 2]

print(oddNumbers)

Output:

[11, 11, 23, 171, 91, 9]

We fetched only odd numbers from the list.

Method 2: Using List Comprehension & AND operator

This solution is similar to previous one. But with just one difference. Although, we will iterate over all numbers of list, and select only odd numbers using List Comprehension. But we will use different logic, to check if a number is odd or not. Apply an AND operation between a number and digit 1, if it returns 1, then it means the given number is odd. Let’s see an example,

# List of Numbers
listOfNumbers = [10, 11, 11, 23, 14, 36, 12, 20, 18, 171, 78, 91, 9, 10]

# Select only odd numbers from a list in Python
oddNumbers = [elem for elem in listOfNumbers if elem & 1]

print(oddNumbers)

Output:

[11, 11, 23, 171, 91, 9]

We fetched only odd numbers from the list.

Method 3: Using For Loop

This solution is similar to previous one. But with just one difference. We will use direct for loop, instead of List Comprehension. Iterate over all numbers in list using a for loop, and select odd numbers only. To check if a given number is odd or not, divide it by 2. If the reminder is 1, then it means the given number is odd. Let’s see an example,

# List of Numbers
listOfNumbers = [10, 11, 11, 23, 14, 36, 12, 20, 18, 171, 78, 91, 9, 10]

# An empty list to hold odd numbers
oddNumbers = []

# Iterate over all elements of list
for elem in listOfNumbers:
    # Check if given element/number is odd
    if elem % 2:
        # If number is odd then add in new list
        oddNumbers.append(elem)

print(oddNumbers)

Output:

[11, 11, 23, 171, 91, 9]

We fetched only odd numbers from the list.

Summary

We learned about three different ways to select only odd numbers from a list in Python. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top