List Comprehension Simplified
List comprehension is a shorthand for creating a new list based on values in another list. You can think of it as a for loop in one line of code. List comprehension makes it easy to transform list values and filter a list. List comprehension comes in handy during data cleaning and preprocessing.
Advantages of using list comprehension
It’s faster than an ordinary for-loop
It’s one line of code which gives your code a cleaner appearance
Disadvantages of list comprehension
It can get quite complex and difficult to debug
It isn’t very readable for people who are unfamiliar with it
How to use list comprehension in your code
List comprehension is simple and intuitive once you get the hang of it. The syntax is as follows:
[item expression for an item in existing list]
Let’s break down each of the elements of list comprehension:
item - this is the iterator variable
expression - the operation you want to perform on the variables in the existing list to create the new list
existing list - the list that serves as the basis for your list comprehension
And that’s how you create a list using list comprehension. You have to wrap everything after the assignment operator in square brackets. Python will throw an error if this is not done. This is a common error when using list comprehension.
How to use list comprehension
Let’s look at examples of how to use list comprehension.
Creating a new list by multiplying values in another list by two
# Creating a new list using a for loop
numbers = [1, 2, 3, 4, 5]
multiply_two = []
for i in numbers:
multiply_two.append(i*2)
# Creating a new list using list comprehension
multiply_two = [i * 2 for i in numbers]
Filtering and creating a new list
# Filtering and creating a new list using a for loop with a condition
numbers = [1, 2, 3, 4 ,5]
even_numbers = []
for i in numbers:
if i % 2 == 0:
even_numbers.append(i)
# Filtering a list using list comprehension with a condition
even numbers = [i for i in numbers if i % 2 == 0]
Conclusion
In this tutorial, we covered:
What list comprehension is
The advantages of list comprehension
The disadvantages of list comprehension
When and how to use list comprehension
And that’s a wrap. Happy coding!
Subscribe to my newsletter
Read articles from Pitso directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by