Open In App

Square Each Odd Number in a List using List Comprehension

Last Updated : 05 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The task of squaring each odd number in a list using list comprehension in Python involves iterating through the list, identifying odd numbers, and squaring them while leaving the even numbers unchanged. For example, given a list a = [1, 2, 3, 4, 5, 6, 7], the goal is to square each odd number, resulting in the list [1, 9, 25, 49] while skipping the even numbers.

Using list comprehension

List comprehension is a efficient way to iterate over a list and perform operations like squaring odd numbers. It provides a concise syntax, avoiding the need for explicit loops and intermediate steps, resulting in cleaner code.

Python
a = [1, 2, 3, 4, 5, 6, 7]

res = [i * i for i in a if i % 2 != 0]
print(res)

Explanation: List comprehension iterates over the list a, filtering out even numbers with if i % 2 != 0 and squares each odd number. The squared values are stored in the list res .

Using conditional list comprehension

We can use an inline conditional within list comprehension to square odd numbers and replace even numbers with a default value like 0 . This method allows for flexible handling of both odd and even values in a single expression.

Python
a = [1, 2, 3, 4, 5, 6, 7]

res = [i*i if i % 2 != 0 else 0 for i in a]
print(res)

Explanation: List comprehension iterates over the list a and for each element i, it checks if the number is odd (i % 2 != 0). If the number is odd, it squares the number (i * i), otherwise, it replaces the even number with 0.

Using filter()

Combining filter() with list comprehension enables us to first extract odd numbers and then square them. The filter() function is used to create a list of odd numbers, which is then processed by list comprehension to apply the squaring operation.

Python
a = [1, 2, 3, 4, 5, 6, 7]

res = [i * i for i in filter(lambda x: x % 2 != 0, a)]
print(res)

Explanation: This code filters out even numbers from the list a and then squares the remaining odd numbers.



Next Article

Similar Reads