Hit enter after type your search item

Understand Python list comprehension with 3 examples

The list comprehension in Python

In Python, a list can be constructed by using the list comprehension.

Generally, the list comprehension involves creating a new list where each item of another list or sequence is gone through certain operation (like square, cube etc).

I will show you with 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,

  • The newlst is the list you want to create. It can be any name of the list.
  • The list comprehension consists of brackets that enclose an expression which is followed by the for clause.
  • 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 online:

Python list comprehension

See online demo and code

The code:


 

You can see the second list is the square of 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 the three times of each number in the sequence.

list comprehension range

See online demo and code

The code:


 

The output of the above code is a new list:

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

Constructing a list of Celsius temperature based at Fahrenheit list

A great thing is, you may apply mathematical formulas for creating a new list based at 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:

list comprehension temperature

See online demo and code

The code:


 

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

This div height required for enabling the sticky sidebar