What is list comprehension in Python?
- List comprehension is the concise and expressive way of creating lists in Python.
- Generally, list comprehension involves creating a new list where each item of another list or sequence is gone through a certain operation (like square, cube, etc).
- We will show you examples that how you may create list comprehension, let us first look at its syntax.
Syntax of creating Python list comprehension
The general syntax for creating list comprehension can be:
Where,
newlst | The newlst is the list you want to create. It can be any name for the list. |
brackets | The list comprehension consists of brackets that enclose an expression which is followed by the for clause. |
for or if | After that, you may use zero or more for or if clauses. |
An example of creating list comprehension
In this example, a list is created with five items. After that, a list comprehension is constructed with the square of items of the first list.
See the code and output below:
lst1 = [2,4,6,8,10] lst_compre = [x**2 for x in lst1] print ("The first list:",lst1) print ("A list comprehension:",lst_compre)
Output:
A list comprehension: [4, 16, 36, 64, 100]
You can see the second list is the square of the first list elements.
An example of creating list comprehension with range function
In this example, the range function is used for creating a list comprehension. The new list is three times of each number in the sequence.
The code:
lst_compre = [x**3 for x in range(5,25,5)] print ("A list comprehension with range:",lst_compre)
The output of the above code is a new list:
Constructing a list of Celsius temperatures based on Fahrenheit list
A great thing is, you may apply mathematical formulas for creating a new list based on another list or range (or any sequence).
In this example, a list of Fahrenheit temperatures is created. This list of Fahrenheit temperatures is used in creating another list comprehension which is Celsius temperatures. The following conversion formula is applied:
See the code and output below:
f_temp = [98.5, 101,102,203,104] C_temp = [((f-32) * 5/9) for f in f_temp] print ("Celsius temperature :",C_temp)
Output:
You can see that the new list with Celsius temperature is displayed.