This can be done using itertools.chain :
import itertools l1 = [1, 2, 3, 4] l2 = [5, 6, 7, 8] for i in itertools.chain(l1, l2): print(i, end=" ")
Which will print:
1 2 3 4 5 6 7 8
According to the documentation, chain performs the following actions:
Create an iterator that returns items from the first iteration until it is exhausted, then proceeds to the next iteration until all iterations are exhausted.
If you have lists in the list, itertools.chain.from_iterable is available:
l = [l1, l2] for i in itertools.chain.from_iterable(l): print(i, end=" ")
Which gives the same result.
If you do not want to import a module for this, writing a function for it is quite simple:
def custom_chain(*it): for iterab in it: yield from iterab
This requires Python 3, for Python 2, only yield them back using a loop:
def custom_chain(*it): for iterab in it: for val in iterab: yield val
In addition to the previous, Python 3.5 with extended generalizations for unpacking also allows you to unpack a literal in a list:
for i in [*l1, *l2]: print(i, end=" ")
although this is slightly faster than l1 + l2 it still creates a list, which is then discarded; just go for it as a final decision.