How can I achieve to iterate multiple lists in the most pythonic way?
Say I have 2 lists:
l1 = [1, 2, 3]
l2 = [4, 5, 6]
How can I achieve the iteration over the whole set of elements in l1 and l2 without altering l1 and l2?
I can simply join both lists and then iterate over the result:
l3 = l1[:]
l3.extend(l2)
for e in l3:
# ... whatever with e
But that solution does not sounds to me as very pythonic, nor efficient, so I'm looking for a better way.
l1, then iteratel2, in separate loops. If there's too much code in the loops to be worth repeating, just abstract it into a function. However, that being said,chainis almost always the best answer, as F.J suggests. For example, if you wanted to use a genexpr or listcomp or function instead of an explicit loop, you can't just break it into two genexprs. (Well, you can… but only by callingchainon the result, so you might as well justchainat the start…)