What is list comprehension in Python?
List comprehensions are a concise way to create lists. They are used to create a new list by iterating over another list.
Syntax
It consists of square brackets containing an expression followed by the “for” keyword. The result will be a list whose results match the expression.
The basic syntax is :
newlist = [output_expression(x) for x in oldlist if conditional(x)]
The above syntax is explained through the illustration below:
Parameters
The list comprehension basically consists of four parameters.
- Output expression: Defines the output of the list
- Oldlist: Defines the list which is to be traversed
- Conditional/predicate: Defines a condition on variable x. This is an optional parameter.
- Newlist: Save the result of list expression in the newlist
Example 1
The following code creates a list containing the square of numbers:
l1=[] #declare an empty listl1=[x*x for x in [0, 1, 2, 3]] #store the result of list comprehension in l1print (l1)#print the list
Example 2
The following code uses a predicate expression and stores only the square of those numbers in the list which is divisible by 2:
l1=[] #declare an empty listl1=[x*x for x in [0, 1, 2, 3] if (x%2==0)] #store the result of list comprehension in l1print (l1)#print the list
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved