List Comprehensions in Python is the creation of new lists from an iterable object satisfying a given condition.
List comprehensions are generally a one-liner code that performs a specific task.
Let’s see one example,
Consider an algorithm to print the integers from 1 to 10.
First Approach : Traditional Algo
integers = []
for i in range(1, 11):
integers.append(i)
print(integers)
O/P
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
So, let’s see if we can do this in a more precise way using list comprehension.
Second Approach : List Comprehensions
integers = [i for i in range(1,11)]
print(integers)
O/P
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Syntax
[expression for item in iterable if condition]
So, whenever you want to define a list comprehension, keep this syntax in mind.
To get more clearer picture of this, let’s go-through some of the examples
Just like List Comprehensions, we also have set comprehension, dictionary comprehension etc.
Problem 1: List Comprehension to print square of even integers from 1 to 20.
square = [ i * i for i in range(1, 21) if i % 2 == 0 ]
print(square)
O/P
[4, 16, 36, 64, 100, 144, 196, 256, 324, 400]
Problem 2: List Comprehension to print all elements of nested list.
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
square = [ j for i in l for j in i ]
print(square)
O/P
[1, 2, 3, 4, 5, 6, 7, 8, 9]
List Comprehension is fun and simple. No ?

Good to know!