How to loop in a list more times than the list size?

Question:

Is there a function or native lib in Python that allows me to loop in a list more times than the number of elements in the list? In other words, when my index of interest is greater than the list size, the next element is the first of the list.

For example, I have this list:

abc = ['a', 'b', 'c', 'd', 'e']

So, if I have an index with value 10, the result will be 'a'. If the index is with value 18, the result will be 'd'.

Asked By: Emmanuel Arias

||

Answers:

Simplest: wrap the index with modulo

>>> abc = ['a', 'b', 'c', 'd', 'e' ]
>>> abc[18 % len(abc)]
'd'

You can wrap it up in a helper class if you want:

>>> class ModList(list):
...     def __getitem__(self, item):
...         if isinstance(item, slice):
...             return super().__getitem__(item)
...         return super().__getitem__(item % len(self))
...     
>>> abc = ModList('abcde')
>>> abc[18]
'd'
>>> abc[-5]
'a'
>>> abc[-6]
'e'

You might want to implement __setitem__ and __delitem__ similarly.

Answered By: wim

itertools.cycle() works if you want to iterate sequentially, repeatedly through the list

from itertools import cycle


abc = ['a', 'b', 'c', 'd', 'e' ]

alfs = ''

for n, e in enumerate(cycle(abc)):  # lazy enumeration?
    alfs += e
    if n >= 18:  # must have stopping test to break infinite loop
        break
alfs
Out[30]: 'abcdeabcdeabcdeabcd'
Answered By: f5r5e5d
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.