Search code examples
pythonindexingcyclepython-itertools

Is it a way to know index using itertools.cycle()?


I need to loop trough a list and come back to first element when last item is reached.

The cycle object from itertools is designed for this.

myList = [1,2,3,4,5,6,7,8,9]

i = 0
for item in cycle(myList):
    index = i%9
    print (index)
    i += 1

Is there any other way than using a i variable?


Solution

  • You can use enumerate:

    for i, item in enumerate(cycle(myList)):
    

    Below is a demonstration:

    >>> from itertools import cycle
    >>> for i, item in enumerate(cycle([1, 2, 3])):
    ...     print i, item
    ...
    0 1
    1 2
    2 3
    3 1
    4 2
    5 3
    

    You can even give a specific number to start at:

    for i, item in enumerate(cycle([1, 2, 3]), 10): # Start at 10
    

    Reading @DSM's comment, I realize that you may want to flip the calls to cycle and enumerate:

    >>> for i, item in cycle(enumerate([1, 2, 3])):
    ...     print i, item
    ...
    0 1
    1 2
    2 3
    0 1
    1 2
    2 3
    

    This will cause i to refer to the index of item in the list rather than act as a counter variable.