Open In Colab

6: List Comprehension#

List comprehension is a clever way to create lists on a single line of code, which makes the code much faster (because python is a rather slow language)

The two codes below both perform the same operation. We can see (thanks to the %%time command) that the execution time with list comprehension is much less than the execution time with the append() method

%%time
liste = []
for i in range(100000):
    liste.append(i**2)
CPU times: user 46.9 ms, sys: 0 ns, total: 46.9 ms
Wall time: 45.7 ms
%%time
liste = [i**2 for i in range(100000)]
CPU times: user 37 ms, sys: 58 µs, total: 37 ms
Wall time: 36.6 ms

You can add if conditions in the comprehension lists, for example :

liste = [i**2 for i in range(100000) if (i % 2) == 0] # compute i**2 only for even numbers

print(liste[:10]) #displays the first 10 elements of the list
[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]

Exercise and solution#

The same principle applies to dictionaries! So try to create a dictionary that contains keys from 1 to 20, with the square value of each key

Solution#

Hide code cell content
dictionary = {k : k**2 for k in range(1, 21)}
print(dictionary)
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225, 16: 256, 17: 289, 18: 324, 19: 361, 20: 400}