1

Say, I have two lists a and b:

a = [10, 20]
b = [40, 50]

I want to loop over all these values (10, 20, 40, 50) in one go.

Simply doing two loops is not what I want (repetition is ugly).

I also don't want to modify one of the lists:

a.extend(b)
for i in a:
    print(i)

So how do I do this elgantly in Python?

florisla
  • 12,668
  • 6
  • 40
  • 47

2 Answers2

8

You can use chain from itertools:

from itertools import chain

a = [10, 20]
b = [40, 50]

for i in chain(a, b):
    print(i)

This will not create a new list (as a + b does) and is therefore more (memory-)efficient should your lists be huge.

This also works for generators and other iterables.

pillravi
  • 4,035
  • 5
  • 19
  • 33
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111
1
for i in a + b:
    print(i)

Note: I answered this myself. Was wondering about the question, found the answer but not through SO, and felt that it should be added.

Delgan
  • 18,571
  • 11
  • 90
  • 141
florisla
  • 12,668
  • 6
  • 40
  • 47