What is a List Comprehension in Python?

List Comprehension is an alternate syntax of creating a new list using the already existing list. So, instead of using the for loop and the append() function, list comprehension provides a single line of code in which you loop through each item of the existing list and create a new list.

How to make a list comprehension in Python?

You must understand that list comprehension is considered a powerful feature of Python, and to make a list comprehension, you must follow the following format.

[expression if...else for item in iterable if condition]

The explanation of the components present in list comprehension is:

  1. An expression can be one of the following:
    • An item itself.
    • A function call.
    • A valid expression that returns a value.
  2. An iterable can be a list or any other object like range() function that returns one item at a time.
  3. if condition at the end of the for loop is for filtering the item. When an item satisfies the condition, it is considered a part of the new list; otherwise, it is skipped. It is optional.
  4. if...else statement before the for loop is used for selecting more than one value based on the condition. It is also optional.

Let's see how to use list comprehension in Python with examples.

Copy list using list comprehension?

In the first example, you will learn how to copy a list using list comprehension.

lst = [1, 2, 3, 4, 5, 6]
newList = [i for i in lst]


[1, 2, 3, 4, 5, 6]

Without list comprehension, you have to write the same code in the following way:

lst = [1, 2, 3, 4, 5, 6]
newList = []
for i in lst:

if statement in list comprehension

Next, you will learn how to use if statement in list comprehension.

Suppose you want to create a list of even numbers between 1 and 20. So, you will use if condition after for loop in list comprehension and check whether each number is divisible by 2 or not.

evenNumbers = [number for number in range(1, 21) if number%2==0]


[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Let's see another example in which you will learn how to use logical operators in list comprehension. Suppose you want to create a list of numbers that are divisible by 10 or 11 in the range 1-100.

newList = [number for number in range(1, 101) if number%10==0 or number%11==0]


[10, 11, 20, 22, 30, 33, 40, 44, 50, 55, 60, 66, 70, 77, 80, 88, 90, 99, 100]

It is important to note that you are allowed to use the if...else statement before for loop in list comprehension. So let's see how to use if...else with the help of an example:

Suppose you have a list of floating-point numbers, and you want to create a new list in which you want to determine the floor value of positive numbers and calculate the ceiling value of negative numbers.

import math

prices = [114.32, -3.5, -16.43, 7.31, 1.92]
lst = [math.ceil(price) if price>0 else math.floor(price) for price in prices]


[115, -4, -17, 8, 2]

Recommended Posts