Understanding List Comprehension - Python

·

4 min read

Python is known for apparently being easy to read and code as plain English, but sometimes it is just really hard to understand how to speak its dialect. List comprehension is many coders' first experience in learning how Python can be a whole new can of beans. When using Python as your backend, list comprehension is by far one of the best ways to the relationships of your data. One of the major bonuses to using List Comprehension is that it can add to code readability and shortens the amount you need to type. I will attempt with my limited knowledge to go through why and how to use List comprehension throughout this blog.

When to use List Comprehension.

List Comprehension is a concise way of building a list in Python while adding to its functionality in the backend. It allows you to create new lists by applying operations to each item in an existing list or iterable object.

How to use List Comprehension

Basic Syntax

List comprehension has a simple syntax that consists of three parts:
1. A variable name for each item in the original list
2. A for loop that iterates over each item in the original list.
3. An operation that is performed on each item in the original list and returns a new item for the new list.

All together it looks similar to this

new_list = [ item for item in y (do something)]

The expression can be any valid Python expression that returns a value. The item is a variable name that represents each item in the original list, and iterable is any iterable object such as a list, tuple, or string.

Let's take a look at some examples of List comprehension using standard loops and then with List Comprehension.

Example 1: Squaring Numbers

numbers = [1, 2, 3, 4, 5]
squares = []
for n in numbers:
    squares.append(n**2)
print(squares)
# => Expected Output: [1, 4, 9, 16, 25]

Or we could use List Comprehension to achieve the same result with less code

numbers = [1, 2, 3, 4, 5]
squares = [n** for n in numbers]
print(squares)
# => Expected Output: [1, 4, 9, 16, 25]

In this example, we use the variable name n to represent each item in the original list numbers. The expression is n**2, which squares each number in the list. The result is a new list of squares stored in the variable squares.

Example 2: Filtering a list

List comprehension can also be used to filter items from a list. Suppose we have a list of numbers and we want to create a new list with only the even numbers. We could do this using a for loop and an if statement:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = []
for n in numbers: 
    if n % 2 == 0: 
        evens.append(n) 
print(evens) 
# => Expected Output: [2, 4, 6, 8, 10]

Or we could use list comprehension to achieve the same result with less code:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 
evens = [n for n in numbers if n % 2 == 0]
print(evens) 
# => Output: [2, 4, 6, 8, 10]

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] evens = [n for n in numbers if n % 2 == 0] print(evens) # Output: [2, 4, 6, 8, 10]

Example 3: Creating a List of Tuples

Suppose we have two lists, one with names and one with ages, and we want to create a new list of tuples where each tuple contains a name and age. We can use list comprehension to achieve this in one line of code.

names = ['Alice', 'Bob', 'Charlie'] 
ages = [25, 30, 35] 
name_age_tuples = [(name, age) for name, age in zip(names, ages)]

print(name_age_tuples) 
# => Output: [('Alice', 25), ('Bob', 30), ('Charlie', 35)]

In this example, we use the built-in zip function to combine the two lists into a single iterable object. The variable names and ages represent each item in the respective lists, and we use these variables to create a tuple with the name and age of each person.

The resulting list of tuples is stored in the variable name_age_tuples and printed to the console.

In Conclusion

As we can all see, List Comprehension is a powerful tool that can work through data to create subsets and show concise relationships within a project's backend making Python easily one of the best languages to use as a Backend for any project.