Skip to content
Related Articles

Related Articles

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

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 01 May, 2022

Given a list, the task is to write a Python Program to square each odd number in a list using list comprehension.

Python – 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 a 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]

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]
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!