programming tip

Flatten a list of lists

Usually, we flatten a list of lists using a couple of nested for loops. Although this method works fine, it makes our code larger. So, here’s a shorter method to flatten a list using the itertools module.

import itertools
a = [[1, 2], [3, 4]]
b = list(itertools.chain.from_iterable(a))