How to Use List Comprehensions in Python

Learn everything about List Comprehensions in Python

Picture of Nsikak Imoh, author of Macsika Blog
Abstract background with the text How to Use List Comprehensions in Python
Abstract background with the text How to Use List Comprehensions in Python

Table of Content

List comprehensions are a syntax that's sometimes preferred over loops, as it's more readable when the operation can be written on a single line.

Supposing you have a list of fruits, you want a new list, containing only the fruits with the letter “a” in the name.

Without list comprehension, you will have to write a for statement with a conditional test inside. With list comprehension you can do all that with only one line of code.

What is List Comprehensions in Python

List comprehensions are a way to create lists in a very concise way.

It offers a shorter syntax when you want to create a new list based on the values of an existing list.

List comprehension is generally more compact and faster than normal functions and loops for creating list.

However, we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly.

Remember, every list comprehension can be rewritten in for loop, but every for loop can't be rewritten in the form of list comprehension.

Syntax of List Comprehensions in Python

Here is the syntax of list comprehension in Python:

newlist = [_expression_  for  _item_  in  _iterable_  if  _condition_ == True]
Highlighted code sample.
  • Condition: The condition is like a filter that only accepts the items that valuate to True. The condition is optional and can be omitted.
  • Iterable: The iterable can be any iterable object, like a list, tuple, set etc.
  • Expression: The expression is the current item in the iteration, but it is also the outcome, which you can manipulate before it ends up like a list item in the new list. You can set the outcome to whatever you like such as power of 2 for integers or uppercase for strings. The expression can also contain conditions, not like a filter, but as a way to manipulate the outcome

Example of List Comprehension

Suppose you have a list:

numbers = [1, 2, 3, 4, 5]
Highlighted code sample.

Using For loops

You can create a new list using regular for loop by doing the following:

numbers_power_4 = []
for n in numbers:
    numbers_power_4.append(n**4)
Highlighted code sample.

Using lambda function with map()

numbers_power_4 = list(map(lambda n : n**4, numbers))
Highlighted code sample.

Using List Comprehension

However, you can also create a new list using a list comprehension, composed by the numbers list elements, power 4:

numbers_power_4 = [n**4 for n in numbers]
Highlighted code sample.

How to Use Conditionals in List Comprehension

List comprehensions can utilize conditional statement to modify existing list (or other tuples).

Example of List Comprehension in Python Using “If” Conditionals

We will create list that uses mathematical operators, integers, and range()

number_list = [ x for x in range(20) if x % 2 == 0]
print(number_list)
Highlighted code sample.

Example of List Comprehension in Python Using Nested “If” Conditionals

num_list = [y for y in range(100) if y % 2 == 0 if y % 5 == 0]
print(num_list)
Highlighted code sample.

In the example above, the list comprehension checks:

  1. Can y be divided by 2?
  2. Can y be divided by 5?

If y satisfies both conditions, y is appended to num_list.

Example of List Comprehension in Python Using “If … Else” Conditionals

obj = ["Even" if i%2==0 else "Odd" for i in range(10)]
print(obj)
Highlighted code sample.

How to Use Nested Loops in List Comprehension

Example of Transpose of Matrix using Nested Loops in List Comprehension

Supposing we have a 2D array, use can two forloops to find transpose of the matrix.

transposed = []
matrix = [[1, 2, 3, 4], [4, 5, 6, 8]]

for i in range(len(matrix[0])):
    transposed_row = []

    for row in matrix:
        transposed_row.append(row[i])
    transposed.append(transposed_row)

print(transposed)
Highlighted code sample.

However, we can also perform nested iteration inside a list comprehension.

matrix = [[1, 2], [3,4], [5,6], [7,8]]
transpose = [[row[i] for row in matrix] for i in range(2)]
print(transpose)
Highlighted code sample.

Wrap Off

Without list comprehension you will have to write a for statement with a conditional test inside. With list comprehension you can do all that with only one line of code

We hope this covers everything you need to know about list comprehensions in Python.

If you learned from this tutorial, or it helped you in any way, please consider sharing and subscribing to our newsletter.

Get the Complete Code of Python Code Snippets on Github.

Connect with me.

Need an engineer on your team to grease an idea, build a great product, grow a business or just sip tea and share a laugh?