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>
In [14]:
# Simple List Comprehension
list = [x for x in range(5)]
print(list)
In [3]:
# Generate Squares for 10 numbers
list1 = [x**2 for x in range(10)]
print(list1)
In [15]:
# List comprehension with a filter condition
list2 = [x**2 for x in range(10) if x%2 == 0]
print(list2)
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)
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)
In [1]:
list5 = [x + y for x in [1,2,3,4,5] for y in [10,11,12,13,14]]
print(list5)
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)