List Comprehensions in Python

List comprehensions are a topic a lot of new Python users struggle with. This article seeks to explain the benefits of list comprehensions and how list comprehensions work in a digestible manner.

Single for loop list comprehension

The following code uses a traditional for loop to change each string in a for loop from upper to lower case.

# import time package
import time

uppercase_words_list = ['HAT', 'BAT', 'CAT']

start = time.time()

lowercase_words_traditional = []
for word in uppercase_words_list:
  lowercase_words_traditional.append(word.lower())  # add lowercase word to new list

stop = time.time()

print(lowercase_words_traditional)
## ['hat', 'bat', 'cat']

print('elapsed time:', stop-start)
## elapsed time: 0.023993968963623047

This code uses a list comprehension to perform the same task.

start = time.time()

lowercase_words_list_comprehension = [word.lower() for word in uppercase_words_list]

stop = time.time()

print(lowercase_words_list_comprehension)
## ['hat', 'bat', 'cat']

print('elapsed time:', stop-start)
## elapsed time: 0.013007402420043945

To display how list comprehensions compare to traditional for loops, the key components of the for loop are colored in the code examples1. Refer to the key below for the color coding.

Key:
signature of for loop: SkyBlue
body of for loop: Orange

A list comprehension returns a list. When writing a list comprehension, you first write the item to be appended to the list, word.lower() in this case. This is the body of the for loop in the traditional example, without the .append(). WITH A LIST COMPREHENSION, THE .append() IS IMPLIED. Then, the remainder of the list comprehension is the same as the signature of the for loop, or the first line of the for loop, for word in uppercase_words_list, in this case.

Also note that the list comprehension takes about half the time to complete the same task! While the difference in time between the methods may not always be so stark, list comprehensions are faster than traditional for loops.

Nested for loop list comprehension

The following code uses a traditional for loop to create a list of words containing the letter “m”.

import time

lists_of_animals = [['deer', 'mole'], ['cheetah', 'giraffe'], ['penguin', 'woolly mammoth']]

start = time.time()

m_animals = []
for animal_list in lists_of_animals:
  for animal in animal_list:
    if 'm' in animal:
      m_animals.append(animal)
    
stop = time.time()

print(m_animals)
## ['mole', 'woolly mammoth']

print('elapsed_time:', stop-start)
## elapsed_time: 0.020979881286621094

Then, this code performs the same task with a list comprehension.

start = time.time()

m_animals = [animal for animal_list in lists_of_animals for animal in animal_list if 'm' in animal]
    
stop = time.time()

print(m_animals)
## ['mole', 'woolly mammoth']

print('elapsed_time:', stop-start)
## elapsed_time: 0.013031959533691406

To display how list comprehensions compare to traditional for loops, the key components of the for loop are colored in the code examples. Refer to the key below for the color coding.

Key:
signature of outer for loop: SkyBlue
signature of inner for loop: BluishGreen
filtering operation: Blue
body of for loop: Orange

Same as with single for loop list comprehensions, a nested for loop list comprehension returns a list. You first write the item to be appended to the list. This is the body of the for loop in the traditional example, without the .append(). Again, same for nested for loops, WITH A LIST COMPREHENSION, THE .append() IS IMPLIED. Then, the remainder of the list comprehension is the signatures of the nested for loops IN ORDER. Finally, the filtering operation comes at the end of the list comprehension.

For questions or clarifications regarding this article, contact the UVA Library StatLab: statlab@virginia.edu

View the entire collection of UVA Library StatLab articles.

Oyinkansola Adenekan
StatLab Associate
University of Virginia Library
December 13, 2021

1. The colors used in this article are from the Okabe-Ito palette that is well-suited for color vision deficiencies.↩︎