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
  • 10,965
  • 5
  • 35
  • 46

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
  • 3,791
  • 4
  • 15
  • 32
hiro protagonist
  • 40,708
  • 13
  • 78
  • 98
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
  • 16,542
  • 9
  • 83
  • 127
florisla
  • 10,965
  • 5
  • 35
  • 46