Year-End Discount: 10% OFF 1-year and 20% OFF 2-year subscriptions!

Related Tags

list comprehension
python
list
comprehension

# What is list comprehension in Python?

Learn the 24 patterns to solve any coding interview question without getting lost in a maze of LeetCode-style practice problems. Practice your skills in a hands-on, setup-free coding environment. πͺ

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

RELATED TAGS

list comprehension
python
list
comprehension