Trusted answers to developer questions

What is list comprehension in Python?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

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:

svg viewer

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 list
l1=[x*x for x in [0, 1, 2, 3]] #store the result of list comprehension in l1
print (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 list
l1=[x*x for x in [0, 1, 2, 3] if (x%2==0)] #store the result of list comprehension in l1
print (l1)#print the list

RELATED TAGS

list comprehension
python
list
comprehension
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?