1

Imagine I have 2 iterables of any types let say for example list and string:

a = [1, 2, 3]
b = "abc"

Is there a python friendly concise way to iterate over a and b sequentially (not in parallel like with zip) without tricking (the idea here is that a and b can be anything we just know they are iterables)

So no such thing as:

for i in a + list(b):

Ideally I would have something:

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

that would be equivalent to doing

for i in a:
    print(i)
for i in b:
    print(i)
Didier
  • 11
  • 1
  • 3

3 Answers3

1

What you are looking for is itertools.chain: https://docs.python.org/3.8/library/itertools.html#itertools.chain

You would use it like this:

import itertools
a = [1,2,3]
b = "abc"
for i in itertools.chain(a, b):
    print(i)

which produces

1
2
3
a
b
c
lxop
  • 7,596
  • 3
  • 27
  • 42
1

The "something" you're looking for is itertools.chain:

from itertools import chain

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

1
2
3
a
b
c
Jab
  • 26,853
  • 21
  • 75
  • 114
0

itertools.chain() does the trick. You should keep this library in mind when you are looking for things like this.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268