In this article, I will show you how to work with list comprehension in Python.
Understanding how to work with list comprehension in Python is a must for every programmer.
One of the benefits of list comprehension in Python is that it allows an efficient way for programmers to create lists from an existing one. As a result, it reduces the usage of unnecessary loops.
Need a little refresher on Python? Check out this cheat sheet for reference:
At the end of this article, I am confident that you will be comfortable working with list comprehension in Python as all the concepts will come with code snippets and examples.
Also, there video tutorials on list comprehension are available for Linkedin Learning:
Anyway, without a further a due, let’s get started.
List Comprehension in Python
List comprehension is a concise way of creating a new list from an existing list.
The general idea of creating a new list from an existing one is by using them for a loop. However, list comprehension allows us to avoid that.
You may like: Data Structures & Algorithm in Python – Recursion
Let’s say we have the following list:
myList = [1, 2, 3 ,4 ,5, 6, 7, 8, 9, 10]
Suppose we want to create a new list that contains only the even number from the myList.
Here’s the old-school way of doing that using a for
loop:
myList = [1, 2, 3 ,4 ,5, 6, 7, 8, 9, 10]
newL = []
for num in myList:
num = num * 2
newL.append(num)
print(newL)
Output:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
This way of creating a list from an existing one is simple and basic. Moreover, you can see that the code is lengthy.
But there is a different approach to achieving that same result. And that is list comprehension.
Observe the following syntax:
newList = [ x * 2 for x in myList ]
Here the newList
is a list, where each element or item will be x * 2
for
each x
in myList.
This example is similar to what we saw previously. Same results, but with a different approach.
Let’s print it out to see what we have so far:
print(newList)
Output:
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
And thus, you can see that we have the same result as before.
Read: Loops in Python
List Comprehension with Range Function
We see the range()
function a lot with for
loops in Python.
For example:
l = []
for i in range(0,10):
l.append(i)
print("l: ", l)
The code above creates a new list that uses the range()
function. As a result, the new list contains a number from 0 to 9
.
And the output:
l: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Similarly, we can use the range()
function with the list comprehensions to create a new list.
Here’s how we do it:
l = [ i for i in range(0,10) ]
print("l: ", l)
Output:
l: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The list comprehension has a for
loop in it, and with that, we are using the range()
function.
List Comprehension with If Statement
Now we will take a look into integrating if
statement with list comprehension in Python.
Observe the following code:
l = [1, 2, 3 ,4 ,5, 6, 7, 8, 9, 10]
newL = []
for num in l:
if num % 2 == 0:
newL.append(num)
print("newL: ", newL)
Output:
newL: [2, 4, 6, 8, 10]
This way of creating a new list is the traditional approach. However, we can achieve the same output utilizing list comprehension with if
statement.
Here’s how it works:
l = [1, 2, 3 ,4 ,5, 6, 7, 8, 9, 10]
newL = [ x for x in l if x % 2 ==0 ]
print("newL: ", newL)
Output:
newL: [2, 4, 6, 8, 10]
The output is similar to the previous example.
So it means that each element or item on the new list will be an x
for each x
on the list l
that meets the condition x % 2 == 0
.
Recommended: Python Modules & Packages for Absolute Beginners
List Comprehension with Strings and Tuples
The list comprehension in Python is not only for lists only. We can also use it with Strings and tuples.
Let’s observer the following code:
myString = "Hello World"
l = []
for ch in myString:
l.append(ch)
print("l: ", l)
The code above creates a list from a String. Each element of the list l
represents a character of the String myString.
We have a for
loop that slices each character from the String and appends it to the empty list using the append()
method.
As a result, here’s what we get:
l: ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
On the other hand, I can also perform the same operation through list comprehension.
For example:
myString = "Hello World"
l = [ x for x in myString ]
print("l: ", l)
Here, every element on the new list l
will be x
for each character or x
in myString.
Now, the output:
l: ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
Using list comprehension with tuple is similar to using it with lists. Thus, we can apply the same procedure.
Creating a new list from a tuple:
t = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
l = [ x for x in t ]
print("l: ", l)
Output:
l: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
As you can see that the process is similar to how we use list comprehension with a list.
List Comprehension with Functions
In this part, I will show some of the use cases on integrating list comprehension in Python with functions.
First, I will create a function that takes in a number and multiplies it by 2.
def multiply(x):
return x*2
print(multiply(30))
Output:
60
To integrate our function with list comprehension, I am going to type:
l = [1,2,3,4,5,6,7,8,9,10]
newList = [multiply(x) for x in l]
print(newList)
The code above will populate the new list with the results that the function multiply
returns.
So, for each x
on list l
, the function multiplies the x
it and appends them into the new list.
Conclusion
List comprehension in Python is a complex subject. It is an approach to create a new list from a list, tuple, or even a String.
But, remember that you cannot use list comprehension with dictionaries or sets.
Moreover, you can also integrate if statements or conditions and also functions with a list comprehension. But do know that whenever you use a function, it needs to return a value.
Related: Exception Handling in Python with Examples
I completely understand how there are many other ways to explain how it works. Some even discuss this topic with the term expression. I took a different approach.
Still, if I were to explain using the tern expression, then observe the following syntax:
[ expression for value in list ]
You may have already seen that the results of expression are the elements of the new list.
The loop iterates over a list and returns each value to the expression.
After that, the expression value and stories it on a new list.
The goal was to make sure you understand what each statement, variable, and function does inside the list comprehension itself with code snippets.
But, you may still have confusion. I completely understand that. That’s why go over the article again if you have to.
Lastly, I like to recommend the following video courses on list comprehension in Python from Linkedin Learning:
If you are already past the basics of Python, then this course is worth your attention:
Using list comprehension can be a more efficient way of creating lists from existing ones without looping. Do you agree or not?