How to Use List Comprehension in Python

How to Use List Comprehension in Python

14 Oct 2024
Intermediate
2.48K Views
32 min read

List Comprehension in Python

List Comprehension in Python is a clear and effective method for making lists. By applying an expression to each element in an existing iterable, such as a list or range, you may create new lists. In addition to making your Python code clearer and simpler to understand, list comprehension in Python may let you create code more quickly than you could with a typical loop.

This Python tutorial will walk you through the concepts of list comprehension in Python, such as loop vs. list comprehension, using conditions in list comprehension, and many other topics. If you are new to Python programming, you should review every fundamental idea first. The ideal way to begin with Python Development is with Python Certification Training.

What is List Comprehension in Python?

Let us understand List Comprehension in Python by some points that are:

  • Using list comprehension in Python, you may easily generate a new list by applying an expression to each element in an iterable or existing list.
  • It lets you create clear, simple code on a single line as opposed to several lines filled with loops in Python.
  • You can also add conditions to filter which elements should be included in the new list.
  • List comprehension in Python is faster and more efficient than traditional loops for creating lists.
  • It is great for transforming data, such as squaring numbers, filtering even or odd numbers, or manipulating strings.

Let's look at the basic structure of using list comprehension in a Python program.

Syntax of List Comprehension in Python

new_list = [expression for item in original_list if condition]

Let's understand the Syntax:

  • expression- this will hold what has to be done with each item in the original list.
  • item- this is the variable that holds each element in the original list.
  • original_list-this is the list you are iterating over.
  • condition- it is an optional condition that will help filter elements.

Example of List Comprehension in Python

1. Basic Example

Below is an example to explain better how list comprehension works in Python Compiler.

# Original list
numbers = [1, 2, 3, 4, 5]

# List comprehension to double each number
doubled_numbers = [num * 2 for num in numbers]

print(doubled_numbers)

Here,the expression 'num * 2' will double each number. Both the original list "numbers" and the variable "num," which represents each element in the original list, are accessible.

Output

[2, 4, 6, 8, 10]

2. Iteration using List Comprehension in Python

# Using list comprehension to create a list of the first ten even numbers
even_numbers = [x for x in range(1, 21) if x % 2 == 0]
print(even_numbers)

In this example, we use iteration with list comprehension to print the first ten even numbers from 1 to 21.

Output

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

3. List Comprehension in Matrix

# Using list comprehension to create a 3x3 matrix

matrix = [[j for j in range(1, 4)] for i in range(3)]
print(matrix)

In this example, we can use list comprehension in Python to generate a matrix.

Output

[[1, 2, 3], 
 [1, 2, 3], 
 [1, 2, 3]]

4. Generate an Even List using List Comprehension

# using list comprehension to print an even list from 1 to 20
even_list = [x for x in range(1, 21) if x % 2 == 0]
print(even_list)

Here, we use list comprehension to print an even list.

Output

[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Difference Between 'for' Loop vs. List Comprehension

Traditionally, we use Python for loops when working with lists in Python. It is no doubt more versatile and needed in many cases, but list comprehension offers a more compact and concise way of achieving the same results as compared with for loop. Below is a comparison table based on different aspects:

Aspectfor LoopList Comprehension
SyntaxRequires multiple lines and indentation.Uses a single, concise line.
PerformanceGenerally slower due to more overhead.Typically, it's faster as it's optimized internally.
Code LengthIt requires more lines.It is more concise than a loop.
ReadabilityIt can be more verbose and harder to follow.More readable for simple iterations.
Use CaseSuitable for complex logic and multiple actions.Best for simple transformations or filtering.
FlexibilityMore flexible for handling complicated logic.Less flexible but great for straightforward tasks.

Suppose we have a list of numbers and want to create a new list that will display only the even numbers. To understand the difference, we will try to use both for loops and list comprehension.

Example using Traditional 'for' Loop:

# Original list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Empty list to store even numbers
even_numbers = []

# Loop to filter even numbers
for num in numbers:
    if num % 2 == 0:
        even_numbers.append(num)

print(even_numbers)

Output

[2, 4, 6, 8, 10]

Example using List Comprehension:

# Original list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# List comprehension to filter even numbers
even_numbers = [num for num in numbers if num % 2 == 0]

print(even_numbers)

Output

[2, 4, 6, 8, 10]

As you can see, we got the same output in both cases, but using list comprehension, we did it in a slightly shorter time, in a single line of code.

Read More: Python Developer Salary

Time Duration for List Comprehension and 'for' Loop

Here, we will examine the time duration used by a list comprehension and for loop in an example.

import time

# Using for loop to generate a list of squares
start_time = time.time()  # Start time
squares_for_loop = []
for x in range(1, 1000001):
    squares_for_loop.append(x**2)
end_time = time.time()  # End time
for_loop_duration = end_time - start_time

# Using list comprehension to generate a list of squares
start_time = time.time()  # Start time
squares_list_comprehension = [x**2 for x in range(1, 1000001)]
end_time = time.time()  # End time
list_comprehension_duration = end_time - start_time

# Output the time duration for both methods
print(f"For loop duration: {for_loop_duration} seconds")
print(f"List comprehension duration: {list_comprehension_duration} seconds")

Output

For loop duration: 0.178 seconds
List comprehension duration: 0.145 seconds

In terms of calculation, code space, and time, List comprehension in Python is more effective than for loops. Their writing usually consists of a single line of code. The difference between list comprehension and loops depending on speed is shown in the program below.

Using Conditions in List Comprehension

We can also use conditional statements in list comprehensions. By giving them specific conditions, we can filter out elements from the original list.

Let's try adding an if statement in an example program in Python Editor.

# Original list
words = ["apple", "banana", "orange", "kiwi", "pear", "strawberry"]

# List comprehension to filter words with more than 5 characters
long_words = [word for word in words if len(word) > 5]

print(long_words)

len(word) > 5 is the conditional statement here that will check if the length of the word is greater than 5 or not. If true, only then, will it be displayed.

Output

['banana', 'orange', 'strawberry']

Now try adding an else statement that will specify a default value for elements that don't meet the condition.

# Original list
numbers = [1, 2, 3, 4, 5]

# List comprehension to label even and odd numbers
even_or_odd = ['Even' if num % 2 == 0 else 'Odd' for num in numbers]

print(even_or_odd)

Suppose the element meets the if condition num % 2 == 0, 'Even' will be displayed. Else, 'Odd' will be displayed.

Output

['Odd', 'Even', 'Odd', 'Even', 'Odd']

Nested List Comprehensions

Nested list comprehensions allow us to create lists of lists. They are very useful in creating matrices, lists of lists, or any hierarchical data structures in Python where multiple levels are to be included. Let's try it in an example program in Python Online Compiler.

# Nested list of numbers
matrix = [[1, 2, 3],
          [4, 5, 6],
          [7, 8, 9]]

# Nested list comprehension to transpose the matrix
transposed_matrix = [[row[i] for row in matrix] for i in range(len(matrix[0]))]

print(transposed_matrix)

Here, we have an outer list comprehension that will iterate over each column index 'i' in the range of the number of columns in the matrix 'range(len(matrix[0]))'. The inner list comprehension '[row[i] for row in matrix]' will iterate over each row in the matrix.

Output

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

Some Important Examples for List Comprehension

1. Using If-Else in List Comprehension

An if-else statement may also be used in Python list comprehension to allocate values according to a condition conditionally.

Example

# Using list comprehension with if-else to label numbers as 'Even' or 'Odd'
numbers = range(1, 11)  # Numbers from 1 to 10
labels = ['Even' if x % 2 == 0 else 'Odd' for x in numbers]
print(labels)

Output

['Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even', 'Odd', 'Even']

2. Nested IF with List Comprehension

For list comprehension in Python, you may apply several criteria by using nested if statements. Using nested if with list comprehension is illustrated in the following example.

Example

# Using nested if in list comprehension
numbers = range(1, 11)  # Numbers from 1 to 10
categories = [
    'Divisible by 2 and 3' if x % 2 == 0 and x % 3 == 0
    else 'Divisible by 2' if x % 2 == 0
    else 'Divisible by 3' if x % 3 == 0
    else 'Not Divisible by 2 or 3' for x in numbers
]
print(categories)

Output

['Not Divisible by 2 or 3', 'Divisible by 2', 'Divisible by 3', 'Divisible by 2', 
 'Not Divisible by 2 or 3', 'Divisible by 2 and 3', 'Not Divisible by 2 or 3', 
 'Divisible by 2', 'Divisible by 3', 'Divisible by 2']

3. Displaying Squares of Numbers

Here's how to use list comprehension in Python to display the square of values between 5 and 14.

# Using list comprehension to generate squares of numbers from 5 to 14
squares = [x**2 for x in range(5, 15)]
print(squares)

Output

[25, 36, 49, 64, 81, 100, 121, 144, 169, 196]

4. Toggle the case of each character in a String

In Python, you can use list comprehension to switch the case of each character in a string like follows.

# Input string
input_string = "Hello World"

# Using list comprehension to toggle the case of each character
toggled_string = ''.join([char.lower() if char.isupper() else char.upper() for char in input_string])
print(toggled_string)

Output

hELLO wORLD

5. Transpose of a 2D Matrix

Here's an example of utilizing list comprehension in Python to display a 2D matrix's transposition.

# Define a 2D matrix
matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

# Using list comprehension to transpose the matrix
transpose = [[row[i] for row in matrix] for i in range(len(matrix[0]))]

# Display the transposed matrix
for row in transpose:
    print(row)

Output

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

6. Creating a List of Tuples

Using list comprehension in Python, you may produce a list of tuples from two different lists like follows:

# Two separate lists
list1 = [1, 2, 3]
list2 = ['a', 'b', 'c']

# Using list comprehension to create a list of tuples
tuple_list = [(x, y) for x, y in zip(list1, list2)]

# Display the list of tuples
print(tuple_list)

Output

[(1, 'a'), (2, 'b'), (3, 'c')]

7. Reverse each string in a Tuple

Using tuple comprehension and the [::-1] slicing function in Python, you may reverse each text in a tuple as follows:

# Define a tuple of strings
tuple_of_strings = ("apple", "banana", "cherry")

# Using tuple comprehension to reverse each string
reversed_tuple = tuple(s[::-1] for s in tuple_of_strings)

# Display the reversed tuple
print(reversed_tuple)

Output

('elppa', 'ananab', 'yrrehc')

8. Sum of Digits of Odd Elements

Using list comprehension in Python, you can show the total of all the odd entries in a list by using this method:

# Define a list of numbers
numbers = [12, 23, 34, 45, 56, 67, 78, 89]

# Using list comprehension to find the sum of digits of odd numbers
sum_of_digits = sum(sum(int(digit) for digit in str(num)) for num in numbers if num % 2 != 0)

# Display the result
print(f"Sum of digits of odd elements: {sum_of_digits}")

Output

Sum of digits of odd elements: 58

9. List Comprehensions and Lambda

Python functions are simply represented in abbreviated form via Lambda Expressions. An effective combination is produced by combining lambda and list comprehensions.

# using lambda to print table of 10  
numbers = [] 
  
for i in range(1, 6): 
    numbers.append(i*10) 
  
print(numbers) 

Output

[10, 20, 30, 40, 50]

Advantages of List Comprehension

List comprehension in Python offers several advantages, such as:

  • It allows us to write concisely within a single line of code.
  • It makes the code easier to read and understand.
  • It is rather less complex than traditional 'for' loops, as it doesn't have temporary variables and separate loop constructs.
  • In many cases, list comprehensions can be seen as having higher performance than traditional loops.
  • They support a wide range of operations like filtering, mapping, and nesting.
Read More: Top 50+ Python Interview Questions and Answers
Conclusion
To sum up, list comprehension in Python is an easy-to-use yet effective technique that lets you make lists fast. Compared to utilizing conventional loops, it helps your code be shorter, simpler to read, and frequently quicker. If you are looking for a step-by-step guide to learning and understanding various Python concepts better and using them in real-time applications, enroll in our Python Certification Course right now!

FAQs

A list comprehension in Python is used for writing concise codes to create new lists by applying an operation to each item in an existing one.

The four types of comprehension in Python are:
  1. List Comprehension
  2. Dictionary Comprehension
  3. Set Comprehension
  4. Generator Comprehension

Yes, Python list comprehension is faster than traditionally used for loops for creating lists as they are more optimized for performance.

The two main types of comprehension are:
  1. List Comprehension
  2. Dictionary Comprehension
Share Article
About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this