Friday, December 27, 2024
Google search engine
HomeLanguagesPython Program to Square Each Odd Number in a List using List...

Python Program to Square Each Odd Number in a List using List Comprehension

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




# create a list with 7 integer elements
data=[1,2,3,4,5,6,7]
 
# use list comprehension to get square
# of odd numbers
result = [i*i for i in data if i%2!=0]
 
# display the result
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




# create a list with 7 integer elements
data=[11,23,13,3,1,3,4]
 
# use list comprehension to get square
# of odd numbers
result = [i*i for i in data if i%2!=0]
 
# display the result
print(result)


Output:

[121, 529, 169, 9, 1, 9]

Time Complexity: O(n)

Auxiliary Space: O(n)

Example 3:

Using math.pow()

Python3




#Python Program to Square Each Odd Number in a List using List Comprehension
# create a list with 7 integer elements
data=[11,23,13,3,1,3,4]
 
# use list comprehension to get square
# of odd numbers
import math
result = [int(math.pow(i,2)) for i in data if i%2!=0]
 
# display the result
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




# Python program to square each odd number in a list using filter() and map()
 
# initialize list with some values
lst = [1, 2, 3, 4, 5, 6, 7]
 
# use filter() to get odd numbers and map() to square them
squared_odds = list(map(lambda x: x**2, filter(lambda x: x%2 != 0, lst)))
 
# print the squared odd numbers
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.

RELATED ARTICLES

Most Popular

Recent Comments