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
  • 119,623
  • 25
  • 170
  • 301
Rahadian Wiratama
  • 344
  • 1
  • 4
  • 20

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
  • 21,934
  • 6
  • 42
  • 50