List comprehensions are used to create a new list from existing sequences. It is a tool for transforming a given list into another list
1. Without Comprehensions
Suppose to create a list to store five different numbers such as 10,20,30,40 and 50. Using the for loop, add number five to the existing elements of the original list.
a=[10,20,30,40,50]
for i in range(0,len(a)):
a[i]=a[i]+5
print(a)
#Output
[15,25,35,45,55]
Above code is workable but not an optimal code or the best way to write a code in Python. Using list comprehension, we can replace the loop with a single expression that produces the same result.
2. With Comprehension
The syntax for comprehension is
[ for in if ]
The syntax is designed to read a "Compute the expression for each element in the sequence, if the conditional is true".
#Using List Comprehension
a=[10,20,30,40,50]
a=[x+5 for x in a]
print(a)
#Output
[15,25,35,45,55]
With reference to the above example we can say that, list comprehension contains
a) An Input Sequence
b) A Variable referencing the input sequence
c) An Optimal Expression
e) An Output Expression or Output Variable.
Example 1:
Write a program to create a list with elements 1,2,3,4 and 5. Display even elements of the list using list comprehension.
a=[1,2,3,4,5]
print("Content or original List : ",a)
a=[x for x in a if x%2==0]
print("Even Elements from the List : ",a)
#Output
Content or original List : [1, 2, 3, 4, 5]
Even Elements from the List : [2, 4]
Example 2:
Consider a list with five different Celsius values. Convert all the Celsius values into Fahrenheit with and without using comprehension.
list=[10,20,31.3,40,39.2]
print("Celsius Values : ",list)
celsius=[0,0,0,0,0]
#Without Using Comprehension
for i in range(0,len(list)):
f=((float(9)/5)*list[i]+32)
celsius[i]=f
print("Fahrenheit Values(Without Comprehension) : ",celsius)
#With Comprehension
fahrenheit=[((float)(9)/5)*x+32 for x in list]
print("Fahrenheit Values(With Comprehension) : ",fahrenheit)
#Output
Celsius Values : [10, 20, 31.3, 40, 39.2]
Fahrenheit Values(Without Comprehension) : [50.0, 68.0, 88.34, 104.0, 102.56]
Fahrenheit Values(With Comprehension) : [50.0, 68.0, 88.34, 104.0, 102.56]