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

Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

list comprehension
python
list
comprehension

What is list comprehension in Python?

Educative Answers Team

Tired of LeetCode? 😩

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:

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 ©2022 Educative, Inc. All rights reserved

Tired of LeetCode? 😩

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. 💪

Keep Exploring
Related Courses