1 List Comprehensions

List comprehension is a concise way to create lists in “Python” language. It allows you to generate a new list by applying an expression to each element in an existing iterable, such as a list, tuple, set, or string. You can also filter the elements based on a condition.

1.1 The Basic Usage of List Comprehensions

The basic syntax for list comprehension is shown in Tip 1.

Tip 1: TIPS

new_list = [expression for item in iterable]
  • iterable: An object like a list, and a tuple.

Don’t worry about this structure, I will explain it in the following.

Here’s an example to illustrate how list comprehension works:

# Using list comprehension to achieve the same result in a more concise way
squares = [i**2 for i in range(1, 11)]
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Let’s check each part of the code:

for i in range(1, 11): This part of the code sets up a loop that iterates over the numbers from 1 to 10 (inclusive). In each iteration, the loop variable i takes on the values 1, 2, 3, …, 10.

i**2: This is the expression that applies to each value of i in the iteration. It calculates the square of each number i.

[i**2 for i in range(1, 11)]: This entire code represents the list comprehension. It generates a new list where each element is the square of the corresponding value from the range of numbers 1 to 10.

So, when you run squares = [i**2 for i in range(1, 11)], it will create a list called squares containing the squares of the numbers from 1 to 10. The resulting list is [1, 4, 9, 16, 25, 36, 49, 64, 81, 100].

You can create the above squares list without a list comprehension, but it looks verbose:

# Create a list of squares of numbers from 1 to 10 using a for loop
squares = []
for i in range(1, 11):
    squares.append(i**2)
print(squares)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

1.2 Using List Comprehensions with Filters and Manipulations

You can also use conditions within list comprehension to filter elements based on specific criteria. For instance:

# Using list comprehension with a conditional
evens = [i for i in range(1, 11) if i % 2 == 0]
print(evens)
[2, 4, 6, 8, 10]

If i is an even number, the value is added to the list. In other cases, the condition returns nothing. So if i % 2 == 0 works like a filter.

You can generate the same list using normal loops, but a list comprehension is a preferable way because of the simplicity:

# Create a list of even numbers from 1 to 10 using a for loop
evens = []
for i in range(1, 11):
    if i % 2 == 0:
        evens.append(i)
print(evens)
[2, 4, 6, 8, 10]

In the next example, we will output a grade based on the value of score. You can also use else statements with if statements, however there is no option for elif statements.

# Using if-else statements in list comprehension
grades = ["A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "D" if score >= 60 else "E" for score in [85, 77, 92, 60, 45]]
print(grades)
['B', 'C', 'A', 'D', 'E']

The above code takes [85, 77, 92, 60, 45], and if the value is greater than or equal to 90, the condition returns "A". Else if the value is greater than or equal to 80, it returns "B", and so on.

To explain the structure of the condition, I rewrite the above code using normal loops:

# List Comprehension
# -> Normal Loops without "elif" statements
scores = [85, 77, 92, 60, 45]
grades = []

for score in scores:
    if score >= 90:
        grades.append("A")
    else:
        if score >= 80:
            grades.append("B")
        else:
            if score >= 70:
                grades.append("C")
            else:
                if score >= 60:
                    grades.append("D")
                else:
                    grades.append("E")

# Output the final grades list
print(grades)
['B', 'C', 'A', 'D', 'E']

As you can see in the above code, I used nested if and else statements. These conditions are the same as:

# Normal Loops without "else" statements
# -> Normal Loops with "else" statements
scores = [85, 77, 92, 60, 45]
grades = []

for score in scores:
    if score >= 90:
        grades.append("A")
    elif score >= 80:
        grades.append("B")
    elif score >= 70:
        grades.append("C")
    elif score >= 60:
        grades.append("D")
    else:
        grades.append("E")

# Output the final grades list
print(grades)
['B', 'C', 'A', 'D', 'E']

If you feel the if and else structure in the list comprehension is difficult, you can use a helper function. In the following code, convert_to_grade() is the helper function (*We will cover the “function” in the next article). You can define the separate function that encapsulates the complex condition or manipulation and then call the function within the list comprehension.

# Helper function for list comprehension
def convert_to_grade(score):
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "E"

scores = [85, 77, 92, 60, 45]
grades = [convert_to_grade(score) for score in scores]
print(grades)
['B', 'C', 'A', 'D', 'E']

This looks much easy to understand.

So overall, a list comprehension is a concise way of filtering and manipulating the values and creating a new list.

TIPS

You can create a new list using list comprehension. You can also:

  • filter the values
  • manipulate the values

2 Exercises