List Comprehensions¶
Python creates a shortcut for iteratively creating lists. This shortcut is called a list comprehension. We know that we can create a list iteratively using a for loop as follows:
my_list = []
for i in range(a,b):
value = whatever
my_list.append(value)
The same result can be obtained in a more compact fashion using a list comprehension as follows:
my_list = [value for i in range(a,b)]
Lets see a few examples. In the first example, we will create a list containing the square of all elements in a range.
sq_list = [n**2 for n in range(1,10)]
print(sq_list)
[1, 4, 9, 16, 25, 36, 49, 64, 81]
In a previous example, we were given lists listA
and listB
, and were asked to create a list listC
that contained an elementwise sum of the listA
and listB
. Let’s see how this could be accomplished with a list comprehension.
listA = [13, 18, 23, 42, 27, 22, 36, 17, 44, 34, 35, 33, 41, 43, 12, 45, 29, 37, 14, 15]
listB = [42, 14, 31, 39, 40, 48, 47, 36, 28, 32, 11, 27, 16, 17, 34, 33, 46, 22, 26, 15]
listC = [listA[i] + listB[i] for i in range(0, len(listA))]
print(listC)
[55, 32, 54, 81, 67, 70, 83, 53, 72, 66, 46, 60, 57, 60, 46, 78, 75, 59, 40, 30]