A guide to using list comprehension

by Alex
A guide to using list comprehension

Each programming language has its own features and advantages. One of the iconic features of Python is list comprehension (rarely translated into Russian, but you can use the definition of “list generator”). Comprehension is easy to read and is used by beginners and experienced developers alike. List comprehension is a simplified approach to creating a list that engages the for loop as well as if-else instructions to determine what ends up in the final list.

Benefits of list comprehension

List comprehension has three main advantages.

  1. Simplicity. List comprehension allows you to get rid of for loops, and also makes the code more understandable. JavaScript, for example, has something similar in the form of map() and filter(), but they are more complicated for beginners.
  2. Speed. List comprehension is faster than for loops, which it replaces. This is one of the first points when refactoring Python code.
  3. Functional programming principles. It’s not that important for beginners, but functional programming is an approach in which the data being changed is not changed. Because list comprehensions create a new list without changing an existing list, they can be classified as functional programming.

Creating the first list comprehension

List comprehension is written in square brackets and involves a for loop. The process creates a new list that adds all the items of the original list. As items are added, they can be modified. Let’s start with a simple example: create a list of numbers from 1 to 5 using the range() function.


>>> nums = [n for n in range(1,6)]
>>> print(nums)
[1, 2, 3, 4, 5]

In this example, each value of the range is assigned to the variable n. Each value is returned unchanged and added to a new list. This is the n before the for loop. The iterated object does not have to be the range() function. It can be any iterated value.

List comprehension with modification

Now let’s go a little further and add a change for each value in the loop.


>>> nums = [1, 2, 3, 4, 5]
>>> squares = [n*n for n in nums]
>>> print(squares)
[1, 4, 9, 16, 25]

This example has two changes from the previous code. First, a pre-existing list is used as the source. Second, list comprehension creates a list where each value is the squared value of the original list.

List comprehension with if

Now let’s add an if check so that we don’t add all the values.

>>> nums = [1, 2, 3, 4, 5]
>>> odd_squares = [n*n for n in nums if n%2 == 1]
>>> print(odd_squares)
[1, 9, 25]

The if instruction comes after the loop – in this case order plays a role.

List comprehension with a nested for loop

In the last example, let’s look at an example with a nested for loop.


>>> matrix = [[x for x in range(1, 4)] for y in range(1, 4)]
>>> print(matrix)
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

This may seem a little complicated. But you only have to break the code up a few lines to see that there is nothing special.


matrix = [
[x for x in range(1, 4)]
for y in range(1, 4)
]
print(matrix)

One last example. Let’s create a list of birthdays from a list of dictionaries. To do this we will use familiar tactics.


people = [{
"first_name": "Vasily",
{ "last_name": "Markov",
"birthday": "9/25/1984"
}, {
{ "first_name": "Regina",
{ "last_name": "Pavlenko",
{ "birthday": "8/21/1995"
}]
birthdays = [
person[term]
for person in people
for term in person
if term == "birthday"
]
print(birthdays)

In this example, we first go through people, assigning each dictionary person. After that, we go through each identifier in the dictionary, assigning term keys. If the value of term is birthday, then person[term] adds to the list comprehension.

['9/25/1984', '8/21/1995']

Now you can try working with list comprehension on your own examples. This will make the code faster and more compact.

Related Posts

LEAVE A COMMENT