Python Program to Square Each Odd Number in a List using List Comprehension
Last Updated :
27 Jul, 2023
Given a list, the task is to write a Python Program to square each odd number in a list using list comprehension.
Square Each Odd Number in a List using List Comprehension
List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. A list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. Here we will use list comprehension to make a square of each odd number in a list.
Syntax: newList = [ expression(element) for element in oldList if condition ]
Example 1:
In this example, we will get the square of odd numbers using list comprehension
Python3
data = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ]
result = [i * i for i in data if i % 2 ! = 0 ]
print (result)
|
Output:
[1, 9, 25, 49]
Time Complexity: O(n)
Auxiliary Space: O(n)
Example 2:
In this example, we will get the square of odd numbers using list comprehension.
Python3
data = [ 11 , 23 , 13 , 3 , 1 , 3 , 4 ]
result = [i * i for i in data if i % 2 ! = 0 ]
print (result)
|
Output:
[121, 529, 169, 9, 1, 9]
Time Complexity: O(n)
Auxiliary Space: O(n)
Example 3:
Using math.pow()
Python3
data = [ 11 , 23 , 13 , 3 , 1 , 3 , 4 ]
import math
result = [ int (math. pow (i, 2 )) for i in data if i % 2 ! = 0 ]
print (result)
|
Output
[121, 529, 169, 9, 1, 9]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method 4: Use filter() and map() functions to square each odd number in a list
Step-by-step approach:
- Initialize list with some values
- Use filter() to get odd numbers and map() to square them
- Print the squared odd numbers
Below is the implementation of the above approach:
Python3
lst = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 ]
squared_odds = list ( map ( lambda x: x * * 2 , filter ( lambda x: x % 2 ! = 0 , lst)))
print ( "Squared odd numbers:" , squared_odds)
|
Output
Squared odd numbers: [1, 9, 25, 49]
Time complexity: O(n) due to the use of filter() and map(), where n is the length of the input list.
Auxiliary space: O(n) because we are creating a new list to store the squared odd numbers.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...