Skip to content
Advertisement

Iterating over two lists one after another

I have two lists list1 and list2 of numbers, and I want to iterate over them with the same instructions. Like this:

JavaScript

But that feels redundant. I know I can write for item in list1 + list2:, but it has a price of running-time.

Is there a way do that without loose time?

Advertisement

Answer

This can be done with itertools.chain:

JavaScript

Which will print:

JavaScript

As per the documentation, chain does the following:

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted.

If you have your lists in a list, itertools.chain.from_iterable is available:

JavaScript

Which yields the same result.

If you don’t want to import a module for this, writing a function for it is pretty straight-forward:

JavaScript

This requires Python 3, for Python 2, just yield them back using a loop:

JavaScript

In addition to the previous, Python 3.5 with its extended unpacking generalizations, also allows unpacking in the list literal:

JavaScript

though this is slightly faster than l1 + l2 it still constructs a list which is then tossed; only go for it as a final solution.

Advertisement