1

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.

1
  • 1
    You can always just iterate l1, then iterate l2, 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, chain is 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 calling chain on the result, so you might as well just chain at the start…) Commented Aug 7, 2013 at 20:05

3 Answers 3

6

You can use itertools.chain():

import itertools
for e in itertools.chain(l1, l2):
    print e

This doesn't need to create a temporary list for the iteration, unlike l1 + l2. It will also work for arbitrary iterables and for sequences of different types. For example:

>>> l1 = (1, 2, 3)
>>> l2 = [4, 5, 6]
>>> l1 + l2        # can't loop over l1 + l2...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "list") to tuple
>>> import itertools
>>> for e in itertools.chain(l1, l2):
...     print e
...
1
2
3
4
5
6
Sign up to request clarification or add additional context in comments.

2 Comments

This is the most Pythonic approach, +1
thanks for the answer. I think I have to stop asking for pythonic solutions. I recognize your answer is the pythoniest one, but the one I was looking for is the other one by Rohit Jain. Hummm as I said, I have to stop asking for pythonics, but again thanks. (And it wasn't me who downvoted eh? moreover, I upvoted you :D )
4

You can directly iterate over l1 + l2:

>>> l1 = [1, 2, 3]
>>> l2 = [4, 5, 6]
>>> 
>>> for e in l1 + l2:
...     print e

Comments

1

Use the list concatenation operator, + (i.e, l1 + l2) and iterate over that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.