List comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying anexpressionto each item in an existingiterable(such as alist orrange). 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.
Pythona=[2,3,4,5]res=[val**2forvalina]print(res)
Syntax of List Comprehension
[expressionforiteminiterableifcondition]
- 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 afor loop requires multiple lines to create a new list by iterating over items and manually adding each one. Whereas,list comprehensiondo 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:
Pythona=[1,2,3,4,5]# Create an empty list 'res' to store resultsres=[]# Iterate over each element in list 'a'forvalina:# Multiply each element by 2 and append it to 'res'res.append(val*2)print(res)
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' usingappend() method.
Using list comprehension:
Pythona=[1,2,3,4,5]res=[val*2forvalina]print(res)
Explanation: In the above list comprehension, the iterable is a list 'a',and the expression isval * 2,which multiplies each value from the list by 2.
Conditional Statements in List Comprehension
List comprehensions can includeconditional 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.
Pythona=[1,2,3,4,5]res=[valforvalinaifval%2==0]print(res)
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 9a=[iforiinrange(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 3x3 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)forxinrange(3)foryinrange(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.
Pythonmat=[[1,2,3],[4,5,6],[7,8,9]]res=[valforrowinmatforvalinrow]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 inmat. For each row, it iterates through eachvalin that row and collecting all values into a single list.
Related Articles: