Home/Blog/Programming/Understanding List Comprehension in Python
Home/Blog/Programming/Understanding List Comprehension in Python

Understanding List Comprehension in Python

Fawaz Bokhari
Jan 11, 2024
6 min read

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

In Python, list comprehension is a concise way to create new lists based on existing lists or other iterable objects. In other words, it lets you create a new list based on the values in an already created list. You can combine loops, conditional statements, and expressions into a single line of code with the help of list comprehension.

Unlike other iterative methods, such as for loops, list comprehension is a fast, concise, and elegant approach to creating lists.

List comprehension syntax#

The basic syntax for list comprehension looks like this:

list_comp = [expression for item in iterable if condition]

Let's break down the above syntax:

  • list_comp: This is the name of the new list that will be created based on the values generated by the expression.

  • expression: It represents the operation or a call to a method to be applied to each item in the iterable. The result of which will be added to the new list list_comp.

  • item: It is the variable that represents each item in the iterable.

  • iterable: It is the existing list, set, tuple, string, or any other iterable object that can return its elements one at a time.

  • if condition (optional): This part is used to filter the elements from the iterable based on a condition.

Examples#

Here are a few examples to illustrate the concept of list comprehension:

Filter odd numbers from a list#

Suppose that we have a list from which we want to filter out odd numbers. Here’s how you might do it in the “traditional” way:

numbers = [1, 2, 3, 4, 5]
odd_numbers = []
for i in numbers:
if i % 2 != 0:
odd_numbers.append(i)
print(odd_numbers)

However, for reasons discussed later in this blog, this coding style isn't recommended in Python. Here's how you could use list comprehension to solve the same problem.

numbers = [1, 2, 3, 4, 5]
odd_numbers = [x for x in numbers if x % 2 != 0]
print(odd_numbers)

In line 2 of the above example, [x for x in numbers if x % 2 != 0] returns a new list named odd_numbers using list comprehension. First, it iterates over the numbers list one by one. The element x will be returned and stored in the new list if the specified condition if x % 2 != 0 evaluates to True. Here, expression x simply stores the value of x into a new list.

Manipulate strings using list comprehension#

Below is the code that shows how you can manipulate strings using list comprehension.

word = ['Educative', 'Hello', 'World', 'Amazing', 'Fantastic']
characters = [s for s in word if 'e' in s]
print(characters)

In line 2 in the above code, the expression [s for s in word if 'e' in s] returns True if an element contains a character e. So, the new list will include names that contain e.

Nested list comprehension#

Nested list comprehension in Python allows you to create lists containing other lists. It involves using multiple for clauses and optional if clauses within a single list comprehension.

The basic syntax of a nested list comprehension is as follows:

nested_list = [exp for item1 in iterable1 if cond1
for item2 in iterable2 if cond2
...
for itemN in iterableN if condN]

Examples#

Here are a few examples to illustrate the concept of the nested list comprehension:

Flatten a matrix#

Let's check out the code below to see how list comprehension can be used to represent a matrix.

matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
flatten_matrix = [num for row in matrix for num in row]
print(flatten_matrix)

In the above example, we have a nested list matrix representing a 3x3 matrix. The nested list comprehension [num for row in matrix for num in row] flattens the matrix into a single list. It iterates over each row in the matrix (for row in matrix) and then iterates over each number in the row (for num in row), adding the number to the flatten_matrix.

Filter odd numbers from a nested list#

You can also include conditional statements within nested list comprehensions. Here's an example that demonstrates filtering odd numbers from a nested list:

matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
odd_num = [num for row in matrix for num in row if num % 2 != 0]
print(odd_num)

In line 5 of the above example, the nested list comprehension [num for row in matrix for num in row if num % 2 != 0] iterates over each row in matrix, then iterates over each number in the row, and only adds the number to odd_num if it is odd ( if num % 2 != 0).

Nested list comprehensions provide a powerful way to work with multi-dimensional data and concisely perform complex transformations. However, it's important to strike a balance between readability and complexity, as overly complex nested list comprehensions can become hard to understand.

These are just a few examples of what you can do with list comprehensions in Python.

Benefits of using list comprehension#

List comprehensions in Python offer several benefits compared to traditional for loops and conditional statements. Some of its significant benefits are:

Concise and readable code: List comprehensions allow you to express complex operations in a single line of code. It facilitates writing code in fewer lines.

Faster execution: List comprehensions are generally more time-efficient and space-efficient than traditional loops. Python interpreters can optimize list comprehensions to run faster using built-in functions and operations.

Simplified data transformation: With the help of list comprehensions, you can apply expressions, functions, or operations to each element of an iterable and create a new list based on the transformed values. This simplifies common data transformation tasks like mapping, filtering, and flattening.

Ease of debugging: List comprehensions are self-contained expressions, making debugging easier, resulting in identifying and resolving issues more quickly.

When not to use list comprehension#

Even though list comprehension can make writing code easier, there are situations when it is advisable not to use them. Below are some of these circumstances:

Complex code: If your code is too complex, it is better to avoid list comprehension as it can be difficult to understand the code. You can consider using a for loop or other functions in such a case.

Nested lists: You should not use list comprehension when writing complex operations on matrices because it flattens the code and makes it difficult to understand.

Key points to remember#

Key Points

  • List comprehension is an elegant way to define and create lists based on existing lists.
  • In general, list comprehension is faster and more compact than for loops for constructing lists.
  • Avoid writing very long list comprehensions in one line to ensure that code is user-friendly.
  • Keep in mind that every list comprehension can be rewritten with a for loop, but every for loop can’t be rewritten in the form of list comprehension.

Conclusion#

Although Python list comprehension is widely used in coding, keep in mind that you can develop clean code that accomplishes the task by using your intuition and your ability to use data effectively. This is ultimately the secret to writing Pythonic code!

In this blog, we learned list comprehension with examples in Python, nested list comprehension with conditions, its benefits, and when not to use it in your code.

To continue your learning journey through list comprehension in Python, we recommend the following courses on Educative:

We hope you enjoyed reading this blog as much as we did writing it.

Frequently Asked Questions

What are the four types of comprehension in Python?

The four types of comprehension in Python are list comprehension, dictionary comprehension, set comprehension, and generator expression.


  

Free Resources