List Comprehension

List Comprehension#

List comprehension in Python is a compact way of creating a list from a sequence. It is a short way to create a new list. List comprehension is considerably faster than processing a list using the for loop.

[i for i in iterable if expression]

For instance if you want to change a string to a list of characters. You can use a couple of methods. Let’s see some of them:

word = "Python"
l = [letter for letter in word]
l
['P', 'y', 't', 'h', 'o', 'n']

If you want to generate a list of numbers:

numbers = [i for i in range(11)]
numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
squares = [i * i for i in range(11)]
squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
tpl = [(i, i * i) for i in range(11)]
tpl
[(0, 0),
 (1, 1),
 (2, 4),
 (3, 9),
 (4, 16),
 (5, 25),
 (6, 36),
 (7, 49),
 (8, 64),
 (9, 81),
 (10, 100)]

List comprehension can be combined with if expression.

even_numbers = [i for i in range(21) if i % 2 == 0]
even_numbers
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
odd_numbers = [i for i in range(21) if i % 2 != 0]
odd_numbers
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
positive_even_numbers = [i for i in range(21) if i % 2 == 0 and i > 0]
positive_even_numbers
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened_list = [number for row in list_of_lists for number in row]
flattened_list
[1, 2, 3, 4, 5, 6, 7, 8, 9]