Python List Comprehension
Example 1
Add Integers
number_list = [10, 20, 30]
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?
for_number_plus_5 = []
for x in number_list: for_number_plus_5.append(x + 5) print(number_plus_5)
[15, 25, 35]
Example 2
Integer Multiplication
number_mul_3 = [x * 3 for x in [8, 11, 17]] print(number_mul_3)
[24, 33, 51]
Example 3
String
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
String Length
team_length = [len(team) for team in teams] print(team_length)
[4, 7, 7, 9, 7]
Example 5
Characters in a string
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
Another Characters in a string
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 only to the left of 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
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
single if with chars
enter_sandman_vowels = [character for character in "We're off to never-never land" if character in "aeiou"] print(enter_sandman_vowels)
To start we’re going to create a simple dataframe in python:
Example 10
Multiple If
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
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
number_list = [10, 20, 30]
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
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
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]