List Comprehensions

List comprehensions are quick and concise way to create lists. List comprehensions comprises of an expression, followed by a for clause and then zero or more for or if clauses. The result of the list comprehension returns a list.

It is generally in the form of

returned_list = [<expression> <for x in current_list> <if filter(x)>]

In other programming languages, this is generally equivalent to:

for <item> in <list>
    if (<condition>):
        <expression>

Example 1


In [14]:
# Simple List Comprehension
list = [x for x in range(5)]
print(list)


[0, 1, 2, 3, 4]

Example 2


In [3]:
# Generate Squares for 10 numbers
list1 = [x**2 for x in range(10)]
print(list1)


[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Example 3


In [15]:
# List comprehension with a filter condition
list2 = [x**2 for x in range(10) if x%2 == 0]
print(list2)


[0, 4, 16, 36, 64]

Example 4


In [16]:
# Use list comprehension to filter out numbers
words = "Hello 12345 World".split()
numbers = [w for w in words if w.isdigit()]
print(numbers)


['12345']

Example 5


In [10]:
words = "An apple a day keeps the doctor away".split()
vowels = [w.upper() for w in words if w.lower().startswith(('a','e','i','o','u'))]
for vowel in vowels:
    print(vowel)


AN
APPLE
A
AWAY

Example 6


In [1]:
list5 = [x + y for x in [1,2,3,4,5] for y in [10,11,12,13,14]]
print(list5)


[11, 12, 13, 14, 15, 12, 13, 14, 15, 16, 13, 14, 15, 16, 17, 14, 15, 16, 17, 18, 15, 16, 17, 18, 19]

Example 7


In [2]:
# create 3 lists
list_1 = [1,2,3]
list_2 = [3,4,5]
list_3 = [7,8,9]

# create a matrix
matrix = [list_1,list_2,list_3]

# get the first column
first_col = [row[0] for row in matrix]
print(first_col)


[1, 3, 7]