Python Gem #9: itertools.chain

Adam Marshall
1 min readSep 4, 2017

--

You will often find yourself needing to do an operation on a list of lists — say, sum all of them up. The immediate approach is typically;

intermed = [sum(x) for x in lsofls]
result = sum(intermed)

However, there is an extremely useful function for just these kinds of operations within the itertools module, called chain. Roughly speaking, chain takes in a list of iterables and knits them together into one

chain([1,2,3], [4,5,6]) # ==> itertools.chain object of [1, 2, 3, 4, 5, 6]

This can be achieved for a list of lists by unpacking the list;

chain(*lsofls) # ==> itertools.chain object of [1, 2, 3, 4, 5, 6]

By default the output will be an itertools.chain object, and will need to be passed to a list constructor in order to be used as a list. However, sum , reduce , map and other iterator functions can be used directly on the object itself. Therefore, our original code becomes:

result = sum(chain(*lsofls))

This is a daily series called Python Gems. Each short posts covers a detail, feature or application of the python language that you can use to increase your codes readability while decreasing its length.

--

--