Python List Comprehensions

List comprehensions in Python provide a more concise way to generate a list of values.

Let’s first take a look at a more verbose way to generate a list of new elements. In the below code we iterate over a range of numbers three through nine and create a new list, cubed_values, containing each number cubed.

cubed_values = []
for num in range(3, 10):
cube = num**3
# [27, 64, 125, 216, 343, 512, 729]

There’s nothing wrong with the above code. It’s pretty simple and easy to read.

However, list comprehensions offer us an alternative way to achieve this same result. We can instead condense our logic onto a single line, between the square brackets that will contain the new list. Here is an example of a list comprehension that achieves the same result as our first example.

cubed_values = [num**3 for num in range(3, 10)]print(cubed_values)
# [27, 64, 125, 216, 343, 512, 729]

List comprehensions provide a shorter syntax in which we combine our for loop and the logic necessary to create each new element. As a bonus, we also get to omit the append() method call altogether. Python takes care of appending our new element to the list automatically.

The use of list comprehensions isn’t limited to lists of numbers. We can actually use list comprehensions with any iterable. There are many situations in which you might use a for loop and find list comprehensions useful. Below is an arbitrary example that involves iterating through a string.

doubled_char_string = ''.join([char * 2 for char in "hello"])print(doubled_char_string)
# hheelllloo

We can even add an if condition to our list comprehensions. Below we create a new list (and then join() it into a string) that contains only the consonants from our original string, “consonants”.

str = ''.join([x for x in "consonants" if x not in 'aeiou'])print(str)
# cnsnnts

More practically, we might choose to select only the numbers from a list that are divisible by three.

divisible_by_three = [num for num in range(1, 31) if num % 3 == 0]print(divisible_by_three)
# [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

List comprehensions are a fun way to keep your code concise, but make sure to keep the readability of your code in the forefront of your mind. When in doubt, prioritize clarity over brevity.