Python List Comprehension
List Comprehension allows you to save time by creating a list in one line of code, instead of using a For loop.
This is done by applying an expression to each item in the list.
If you want to watch a YouTube video based around the article, we have embedded one down below.
List Comprehension Syntax
[expression for item in iterable if condition]
An iterable can be a list, dictionary, string, or range. This is anything you can loop through.
Example 1 - New List Add Integer
For our first example, lets create a new list in which we add 5 to each element from the number list.
number_list = [10, 20, 30]
The Expression we use is X+5. The Item is X (values 10, 20, and 30) and out list is number_list
number_plus_5 = [x + 5 for x in number_list] print(number_plus_5)
[15, 25, 35]
What would this look like as a for loop? Let’s take a look.
Initially, we have to have an empty list outside of the for loop.Â
for_number_plus_5 = []
Then inside the for loop we will append each value + 5 from the initial list (number_list) to the for_number_plus_5 list.
for x in number_list: for_number_plus_5.append(x + 5) print(number_plus_5)
[15, 25, 35]
Example 2
Integer multiplication is very similar to the addition example from above.
In this example, we will also put the list directly inside the list comprehension statement.
number_mul_3 = [x * 3 for x in [8, 11, 17]] print(number_mul_3)
[24, 33, 51]
Example 3
The first two examples of list comprehension took a look at numbers. Let’s pivot now to strings. In this example we will use the .upper() method and capitalize all the team names in the teams list.
teams = ['Rays', 'Yankees', 'Red Sox', 'Blue Jays', 'Orioles']
uppercase_teams = [x.upper() for x in teams] print(uppercase_teams)
[‘RAYS’, ‘YANKEES’, ‘RED SOX’, ‘BLUE JAYS’, ‘ORIOELS’]
Example 4
Let’s continue with the string example and now find the length of team names. One thing to mention is we are changing X to team. You can utilize whatever name you want for the item in the list. X or Team is valid.
team_length = [len(team) for team in teams] print(team_length)
[4, 7, 7, 9, 7]
Example 5
Let’s look at Characters within a string. Pass in a string in place of where the list was in the previous examples. We will look at a lyric from a Metallica song.
enter_sandman = [character for character in "We're off to never-never land"] print(enter_sandman)
[‘W’, ‘e’, “‘”, ‘r’, ‘e’, ‘ ‘, ‘o’, ‘f’, ‘f’, ‘ ‘, ‘t’, ‘o’, ‘ ‘, ‘n’, ‘e’, ‘v’, ‘e’, ‘r’, ‘-‘, ‘n’, ‘e’, ‘v’, ‘e’, ‘r’, ‘ ‘, ‘l’, ‘a’, ‘n’, ‘d’]
Example 6
Let’s look at another characters in a string example. This time we want to grab the first character in each string. Using the index[0] allows us to get the first character.
metallica_songs = ['Orion', 'Nothing Else Matters', 'Eye of the Beholder']
first_char = [song[0] for song in metallica_songs] print(first_char)
[‘O’, ‘N’, ‘E’]
Example 7 - If Else Statement
The syntax for using if statements in list comprehensions can be a bit confusing at first
When using if only (i.e. filtering), it goes after the for loop.Â
When using if…else (i.e. conditional expressions), the whole expression goes before the for loop.
bands = ['Metallica', 'NIN', 'A Perfect Circle', 'Northlane']
new_bands = [x if x != "NIN" else "Nine Inch Nails" for x in bands] print(new_bands)
[‘Metallica’, ‘Nine Inch Nails’, ‘A Perfect Circle’, ‘Northlane’]
Example 8 - If Statement
concert_db = [80, 110, 60, 70, 120]
loud_concerts = [db for db in concert_db if db > 60] print(loud_concerts)
[80, 110, 70, 120]
Example 9
Here is another if example. This time we will look at a specific character.
enter_sandman_vowels = [character for character in "We're off to never-never land" if character in "aeiou"] print(enter_sandman_vowels)
Example 10 - Multiple If
When you have multiple if statements, it should still be to the right of the for loop.
numbers = [2, 5, 8, 9, 12, 15, 18, 20, 24]
even_and_divisible_by_3 = [x for x in numbers if x % 2 == 0 if x % 3 == 0] print(even_and_divisible_by_3)
Example 11 - Range
Since range is an iterable, we can use it in place of a list or a string.
numbers_squared = [x ** 2 for x in range(10)] print(numbers_squared)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Example 12 - Function with list comprehension
For the expression side of the list comprehension syntax, we can use a function.
number_list = [10, 20, 30]
Let’s create a function plusfive which adds 5 to a number.
def plusfive(num): return num + 5
number_plus_5_v2 = [plusfive(x) for x in number_list] print(number_plus_5_v2)
[15, 25, 35]
Example 13 - Multiple List Comparison
Bands1 = ['Erra', 'Parkway Drive', 'Beartooth', 'In Flames', 'Insomnium']
Bands2 = ['In Flames', 'Dark Tranquility', 'Insomnium', 'Omnium Gatherum', 'Parkway Drive']
matching_bands = [i for i in Bands1 if i in Bands2] print(matching_bands)
[‘Parkway Drive’, ‘In Flames’, ‘Insomnium’]
Example 14 - Nested List Comprehension
matrix = [[j for j in range(3)] for i in range(5)] print(matrix)
[[0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2], [0, 1, 2]]
Example 15
flat_matrix = [i for j in matrix for i in j] print(flat_matrix)
[0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2, 0, 1, 2]
Ryan is a Data Scientist at a fintech company, where he focuses on fraud prevention in underwriting and risk. Before that, he worked as a Data Analyst at a tax software company. He holds a degree in Electrical Engineering from UCF.