2

I have two lists like

num = [1,2,3,4]
names = ['shiva','naga','sharath','krishna','pavan','adi','mulagala']

I want to print the two lists parallel and if one list(num) ends i want to repeat the first list(num) till second(names) list ends.

now i want the output as

1 for shiva
2 for naga
3 for sarath
4 for krishna
1 for pavan
2 for adi
3 for mulagala
falsetru
  • 357,413
  • 63
  • 732
  • 636
Mulagala
  • 8,231
  • 11
  • 29
  • 48

3 Answers3

6

Using itertools.cycle and zip:

>>> num = [1,2,3,4]
>>> names = ['shiva','naga','sharath','krishna','pavan','adi','mulagala']
>>> import itertools
>>> for i, name in zip(itertools.cycle(num), names):
...     print('{} for {}'.format(i, name))
...
1 for shiva
2 for naga
3 for sharath
4 for krishna
1 for pavan
2 for adi
3 for mulagala
falsetru
  • 357,413
  • 63
  • 732
  • 636
1

You'll want to use a combination of itertools.cycle and itertools.izip. For example:

>>> num = [1,2,3,4]
>>> names = ['shiva','naga','sharath','krishna','pavan','adi','mulagala']
>>> import itertools
>>> list(itertools.izip(itertools.cycle(num), names))
[(1, 'shiva'), (2, 'naga'), (3, 'sharath'), (4, 'krishna'), (1, 'pavan'), (2, 'adi'), (3, 'mulagala')]
jterrace
  • 64,866
  • 22
  • 157
  • 202
0

list(roundrobin('ABC', 'D', 'EF'))

output : ['A', 'D', 'E', 'B', 'F', 'C']

from itertools import chain, izip_longest
def roundrobin(*iterables):
    sentinel = object()
    return (x for x in chain(*izip_longest(fillvalue=sentinel, *iterables)) if x is not sentinel)
Neeraj Sharma
  • 1,322
  • 10
  • 9