Here is a simple python for loop:
list_i = []
for i in range(5):
list_i.append(i)
Notice that append() function is called to add elements to the list.
Let’s write the same using List comprehension:
list_i = [i for i in range(5)]
The simplest way to understand why list comprehensions are faster is by noticing that in the first example, append() function is called explicitly. But in list comprehension, it is in-built.
for loop time = time taken for looping + executing append() function
list comprehension = built-in looping and building a list
Some more examples of list comprehensions:
- Square of a number.
list_i = [i*i for i in range(5)]
- Subtract each number by a given number 10
list_i = [10-i for i in range(5)]
- Add 5 to each number.
list_i = [i + 5 for i in range(5)]
Introducing conditions in list comprehensions.
- Even numbers between 1 to 20
list_i = [i for i in range(1,21) if i % 2 == 0]
- Return even numbers given a list of numbers.
numbers = [2,1,4,5,3,9,10,24,36,72,88]
list_i = [i for i in numbers if i % 2 == 0]
Using Dictionaries in List comprehensions
- Given a dictionary, find all keys whose value is ‘3’
a = {'a': 3, 'b': 2, 'c': 3, }
keys = [k for k, v in a.items() if v == 3]
- Given a dictionary where value of key is a list, find all keys that has ‘5’ in it’s value.
a = {1: [2,4,6],
2: [5,6,7],
6: [8,9,5]}
print [k for k, v in a.items() if 5 in a[k]]