4

In my python code, I have two iterable list.

num = [1, 2, 3 ,4 ,5 ,6 ,]

alpa = ['a', 'b', 'c', 'd']

for (a, b) in itertools.izip_longest(num, alpa):

   print a, b

the output:

1 a
2 b
3 c
4 d
5 None
6 None

my expected output:

1 a
2 b
3 c
4 d
5 a
6 b

How do I make it happen?

martineau
  • 112,593
  • 23
  • 157
  • 280

1 Answers1

4

You can use itertools.cycle. Here is some Python 3 code. Note that zip is used rather than izip_longest since cycle creates an infinite iterator and you want to stop when the one list is finished.

import itertools

num = [1, 2, 3, 4, 5, 6] 

alpa = ['a', 'b', 'c', 'd'] 

for (a, b) in zip(num, itertools.cycle(alpa)):

   print(a, b)
Rory Daulton
  • 20,571
  • 5
  • 39
  • 47