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.
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:
expressioncan be one of the following:
iterablecan be a list or any other object like
range()function that returns one item at a time.
forloop 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.
forloop 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.
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] print(newList)
[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: newList.append(i) print(newList)
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] print(evenNumbers)
[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] print(newList)
[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] lst
[115, -4, -17, 8, 2]