The Wayback Machine - https://web.archive.org/web/20241130121329/https://www.geeksforgeeks.org/python-list-comprehension/
Open In App

List Comprehension in Python

Last Updated : 22 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
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.

Python
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:

Python
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:

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

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

Python
# 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.

Python
# 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.

Python
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:



Previous Article
Next Article

Similar Reads

Python List Comprehension | Segregate 0's and 1's in an array list
You are given an array of 0s and 1s in random order. Segregate 0s on left side and 1s on right side of the array. Examples: Input : arr = [0, 1, 0, 1, 0, 0, 1, 1, 1, 0] Output : [0, 0, 0, 0, 0, 1, 1, 1, 1, 1] We have existing solution for this problem please refer Segregate 0s and 1s in an array link. We can solve this problem quickly in Python usi
2 min read
Appending Item to Lists of list using List Comprehension | Python
If you are a Python user, you would know that in Python, we can use the append() method to add an item to an existing list. This list may already contain other items or be empty. Further, the item to be added can simply be a number a character, or even an entire tuple or list. However, if you are trying to append an item to lists within a list comp
5 min read
Count set bits using Python List comprehension
Write an efficient program to count number of 1s in binary representation of an integer. Examples: Input : n = 6 Output : 2 Binary representation of 6 is 110 and has 2 set bits Input : n = 11 Output : 3 Binary representation of 11 is 1101 and has 3 set bits We have existing solution for this problem please refer Count set bits in an integer link. W
2 min read
Python List Comprehension to find pair with given sum from two arrays
Given two unsorted arrays of distinct elements, the task is to find all pairs from both arrays whose sum is equal to x. Examples: Input : arr1 = [-1, -2, 4, -6, 5, 7] arr2 = [6, 3, 4, 0] x = 8 Output : [(5, 3), (4, 4)] Input : arr1 = [1, 2, 4, 5, 7] arr2 = [5, 6, 3, 4, 8] x = 9 Output : [(1, 8), (4, 5), (5, 4)] We have existing solution for this pr
2 min read
Python List Comprehension | Sort even-placed elements in increasing and odd-placed in decreasing order
We are given an array of n distinct numbers, the task is to sort all even-placed numbers in increasing and odd-place numbers in decreasing order. The modified array should contain all sorted even-placed numbers followed by reverse sorted odd-placed numbers. Note that the first element is considered as even because of its index 0. Examples: Input: a
2 min read
Python List Comprehension | Three way partitioning of an array around a given range
Given an array and a range [lowVal, highVal], partition the array around the range such that array is divided in three parts. 1) All elements smaller than lowVal come first. 2) All elements in range lowVal to highVal come next. 3) All elements greater than highVal appear in the end. The individual elements of three sets can appear in any order. Exa
3 min read
Python | List comprehension vs * operator
* operator and range() in python 3.x has many uses. One of them is to initialize the list. Code : Initializing 1D-list list in Python # Python code to initialize 1D-list # Initialize using star operator # list of size 5 will be initialized. # star is used outside the list. list1 = [0]*5 # Initialize using list comprehension # list of size 5 will be
2 min read
How to handle a Python Exception in a List Comprehension?
An exception is something that interrupts the flow of the program. These exceptions stop the process running and sends out an error message. Exceptions can be simply viewed as an object that represents an error. There are predefined exceptions and user-defined exceptions in Python. In this article, we will discuss how to handle Python exception in
5 min read
Python List Comprehension and Slicing
List comprehension is an elegant way to define and create a list in python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp. A list comprehension generally consists of these parts : Output expression,Input sequence,A variable representing a member of the input sequence
5 min read
Move all zeroes to end of array using List Comprehension in Python
Given an array of random numbers, Push all the zeros of a given array to the end of the array. For example, if the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}, it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. The order of all other elements should be same. Expected time complexity is O(n) and extra space is O(1). Examples: Input : a
2 min read
K’th Non-repeating Character in Python using List Comprehension and OrderedDict
Given a string and a number k, find the k-th non-repeating character in the string. Consider a large input string with lacs of characters and a small character set. How to find the character by only doing only one traversal of input string? Examples: Input : str = geeksforgeeks, k = 3 Output : r First non-repeating character is f, second is o and t
2 min read
Break a list comprehension Python
Python's list comprehensions offer a concise and readable way to create lists. While list comprehensions are powerful and expressive, there might be scenarios where you want to include a break statement, similar to how it's used in loops. In this article, we will explore five different methods to incorporate the 'break' statement in Python list com
2 min read
List comprehension and Lambda Function in Python
List comprehension is an elegant way to define and create a list in Python. We can create lists just like mathematical statements and in one line only. The syntax of list comprehension is easier to grasp. A list comprehension generally consists of these parts : Output expression,Input sequence,A variable representing a member of the input sequence
3 min read
Map vs List comprehension - Python
The map() function is used to apply a given function to every item of an iterable, such as a list or tuple and returns a map object (which is an iterator). Whereas, 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
3 min read
Filtering Elements In List Comprehension
List comprehensions are a powerful and concise way to create lists in Python. One of their notable features is the ability to filter elements based on certain conditions. In this article, we will delve into the art of filtering elements in list comprehensions, showcasing simple methods to enhance the readability and efficiency of your code. Syntax:
2 min read
Python Dictionary Comprehension
Like List Comprehension, Python allows dictionary comprehensions. We can create dictionaries using simple expressions. A dictionary comprehension takes the form {key: value for (key, value) in iterable} Python Dictionary Comprehension ExampleHere we have two lists named keys and value and we are iterating over them with the help of zip() function.
4 min read
Why No Python Tuple Comprehension?
In Python, there is no direct tuple comprehension, Python supports list comprehension, set comprehension, and dictionary comprehension. The absence of tuple comprehension is rooted in Python's design philosophy and the characteristics of tuples themselves. The list comprehensions allow for creating lists dynamically, dictionary comprehensions for d
3 min read
How has Verbal Ability and Reading Comprehension (VARC) in CAT changed over the years?
The CAT exam is a computer-based exam in India for admission into the MBA programs of various management institutes of the country such as IIM’s, FMS, DMS, , etc. CAT is organized by one of the IIM’s on a rotational basis and consequently, it is notorious for changing the exam schedule or pattern on a regular basis. Currently, CAT is divided into t
6 min read
Python | Convert list of string to list of list
Many times, we come over the dumped data that is found in the string format and we require it to be represented in the actual list format in which it was actually found. This kind of problem of converting a list represented in string format back to la ist to perform tasks is quite common in web development. Let's discuss certain ways in which this
7 min read
Python | Maximum sum of elements of list in a list of lists
Given lists in a list, find the maximum sum of elements of list in a list of lists. Examples: Input : [[1, 2, 3], [4, 5, 6], [10, 11, 12], [7, 8, 9]] Output : 33 Explanation: sum of all lists in the given list of lists are: list1 = 6, list2 = 15, list3 = 33, list4 = 24 so the maximum among these is of Input : [[3, 4, 5], [1, 2, 3], [0, 9, 0]] Outpu
4 min read
Python | Sort list of list by specified index
We can sort the list of lists by using the conventional sort function. This sort the list by the specified index of lists. Let's discuss certain ways in which this task can be performed using Python. Method 1: Using the bubble sort algorithm Bubble sort is a simple sorting algorithm that repeatedly steps through the list to be sorted, compares each
8 min read
Python | Remove all values from a list present in other list
Sometimes we need to perform the operation of removing all the items from the lists that are present in another list, i.e we are given some of the invalid numbers in one list which need to be get ridden from the original list. Let's discuss various ways How to remove the elements of a list from another list in Python. Illustration: Input: List one
10 min read
Python | Sort list according to other list order
Sorting is an essential utility used in majority of programming, be it for competitive programming or development. Conventional sorting has been dealt earlier many times. This particular article deals with sorting with respect to some other list elements. Let's discuss certain ways to sort list according to other list order. Method #1 : Using List
5 min read
Python | Ways to Convert a 3D list into a 2D list
List is a common type of data structure in Python. While we have used the list and 2d list, the use of 3d list is increasing day by day, mostly in case of web development. Given a 3D list, the task is to convert it into a 2D list. These type of problems are encountered while working on projects or while contributing to open source. Below are some w
3 min read
Python | Merge List with common elements in a List of Lists
Given a list of list, we have to merge all sub-list having common elements. These type of problems are very frequent in College examinations and while solving coding competitions. Below are some ways to achieve this. Input: [[11, 27, 13], [11, 27, 55], [22, 0, 43], [22, 0, 96], [13, 27, 11], [13, 27, 55], [43, 0, 22], [43, 0, 96], [55, 27, 11]] Out
3 min read
Python | Subtract two list elements if element in first list is greater
Given two list, If element in first list in greater than element in second list, then subtract it, else return the element of first list only.Examples: Input: l1 = [10, 20, 30, 40, 50, 60] l2 = [60, 50, 40, 30, 20, 10] Output: [10, 20, 30, 10, 30, 50] Input: l1 = [15, 9, 10, 56, 23, 78, 5, 4, 9] l2 = [9, 4, 5, 36, 47, 26, 10, 45, 87] Output: [6, 5,
5 min read
Python - Filter the List of String whose index in second List contains the given Substring
Given two lists, extract all elements from the first list, whose corresponding index in the second list contains the required substring. Examples: Input : test_list1 = ["Gfg", "is", "not", "best", "and", "not", "CS"], test_list2 = ["Its ok", "all ok", "wrong", "looks ok", "ok", "wrong", "thats ok"], sub_str = "ok" Output : ['Gfg', 'is', 'best', 'an
10 min read
Python | Index of Non-Zero elements in Python list
Sometimes, while working with python list, we can have a problem in which we need to find positions of all the integers other than 0. This can have application in day-day programming or competitive programming. Let's discuss a shorthand by which we can perform this particular task. Method : Using enumerate() + list comprehension This method can be
6 min read
Filter Python list by Predicate in Python
In this article, we will discuss how to filter a python list by using predicate. Filter function is used to filter the elements in the given list of elements with the help of a predicate. A predicate is a function that always returns True or False by performing some condition operations in a filter method Syntax: filter(predicate, list) where, list
2 min read
List Methods in Python | Set 1 (in, not in, len(), min(), max()...)
List methods are discussed in this article. 1. len() :- This function returns the length of list. List = [1, 2, 3, 1, 2, 1, 2, 3, 2, 1] print(len(List)) Output: 10 2. min() :- This function returns the minimum element of list. List = [2.3, 4.445, 3, 5.33, 1.054, 2.5] print(min(List)) Output: 1.054 3. max() :- This function returns the maximum eleme
2 min read
three90RightbarBannerImg