Open In App

List Comprehension in Python

Last Updated : 22 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

List comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques.

For example, if we have a list of integers and want to create a new list containing the square of each element, we can easily achieve this using list comprehension.

a = [2,3,4,5]

res = [val ** 2 for val in a]

print(res)

Output
[4, 9, 16, 25]

Syntax of list comprehension

[expression for item in iterable if condition]

  • expression: The transformation or value to be included in the new list.
  • item: The current element taken from the iterable.
  • iterable: A sequence or collection (e.g., list, tuple, set).
  • if condition (optional): A filtering condition that decides whether the current item should be included.

This syntax allows us to combine iteration, modification, and conditional filtering all in one line.

for loop vs. list comprehension

The main difference is that a for loop requires multiple lines to create a new list by iterating over items and manually adding each one. Whereas, list comprehension do the same task in a single line, this makes the code simpler and easier to read.

Example: Let’s take an example, where we want to double each number of given list into a new list

Using a for loop:

a = [1, 2, 3, 4, 5]

# Create an empty list 'res' to store results
res = []

# Iterate over each element in list 'a'
for val in a:
  
    # Multiply each element by 2 and append it to 'res'
    res.append(val * 2)

print(res)

Output
[2, 4, 6, 8, 10]

Explanation: Create an empty list ‘res‘ to store results and iterate over each element in list ‘a‘ and for each items in list ‘a‘, multiply it by 2 and append it to ‘res‘ using append() method.

Using list comprehension:

a = [1, 2, 3, 4, 5]

res = [val * 2 for val in a]

print(res)

Output
[2, 4, 6, 8, 10]

Explanation: In the above list comprehension, the iterable is a list ‘a’, and the expression is val * 2, which multiplies each value from the list by 2.

Conditional statements in list comprehension

List comprehensions can include conditional statements to filter or modify items based on specific criteria. These conditionals help us create customized lists quickly and making the code cleaner and more efficient.

Example: Suppose we want to filter all even list from the given list.

a = [1, 2, 3, 4, 5]

res = [val for val in a if val % 2 == 0]

print(res)

Output
[2, 4]

To learn more about filtering conditions in list comprehensions, please refer to “Python List Comprehension Using If-Else

Examples of list comprehension

Creating a list from a range

A simple example is creating a list of numbers from 0 to 9.

# Creates a list of numbers from 0 to 9
a = [i for i in range(10)]

print(a)

Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Using nested loops

List comprehension can also be used with nested loops. Here, we generate a list of coordinate pairs for a simple 3×3 grid.

# Creates a list of tuples representing all combinations of (x, y)
# where both x and y range from 0 to 2.
coordinates = [(x, y) for x in range(3) for y in range(3)]

print(coordinates)

Output
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

Flattening a list of lists

Suppose we have a list of lists and we want to convert it into a single list.

mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

res = [val for row in mat for val in row]

print(res)

Output
[1, 2, 3, 4, 5, 6, 7, 8, 9]

Explanation: The line [val for row in mat for val in row] uses nested list comprehension to iterate through each row in mat. For each row, it iterates through each val in that row and collecting all values into a single list.

Related Articles:



Next Article

Similar Reads

three90RightbarBannerImg