List Comprehensions in Python

Sometimes we want to do some very simple operations over the items of a list.

Instead of using the same old way of iterating through lists, we can make our code simpler by using list comprehensions.

Basic syntax

To use a list comprehension to replace a regular for loop, we can make:

[expression for item in list]

Which is the same as doing:

for item in list:
    expression

If we want some conditional to apply the expression, we have:

[expression for item in list if conditional ]

Which is the same as doing:

for item in list:
    if conditional:
        expression

Example 1: calculating the cube of a number

Regular way

numbers = [1, 2, 3, 4, 5]
new_list = []

for n in numbers:
    new_list.append(n**3)

print(new_list)
[1, 8, 27, 64, 125]

Using list comprehensions

numbers = [1, 2, 3, 4, 5]
new_list = []

new_list = [n**3 for n in numbers]

print(new_list)
 [1, 8, 27, 64, 125]

Example 2: calculating the cube of a number only if it is greater than 3

Using the conditional, we can filter only the values we want the expression to be applied to.

Regular way

numbers = [1, 2, 3, 4, 5]
new_list = []

for n in numbers:
    if(n > 3):
        new_list.append(n**3)

print(new_list)
[64, 125]

Using list comprehensions

numbers = [1, 2, 3, 4, 5]
new_list = []

new_list = [n**3 for n in numbers if n > 3]

print(new_list)
[64, 125]

Example 3: calling functions with list comprehensions

We can also call functions using the list comprehension syntax:

numbers = [1, 2, 3, 4, 5]
new_list = []

def cube(number):
    return number**3

new_list = [cube(n) for n in numbers if n > 3]

print(new_list)
 [64, 125]

And that’s it for list comprehensions in Python, one more tool under your developer belt.

To know more about loops, check these posts on for Loops in Python and While Loops in Python.

Watch on Youtube

You can also watch this content on Youtube: