Search code examples
pythonlistround-robin

How to work with two lists as round robin python


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

Solution

  • 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