Understand Python List Comprehensions

A visual guide to understand list comprehension in Python. Learn the syntax, features, use cases and an example.

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:

newlst = [x for x in iterable]

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:

The first list: [2, 4, 6, 8, 10]
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:

A list comprehension with range: [125, 1000, 3375, 8000]

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:

C = (F -32) * 5/9

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:

Celsius temperature : [36.94444444444444, 38.333333333333336, 38.888888888888886, 95.0, 40.0]

You can see that the new list with Celsius temperature is displayed.

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!