5

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'.

2
  • Use the modulo operator. Commented Apr 26, 2018 at 1:33
  • You can create infinite sequence from you abc array with the function cycle(seq) from itertools module and then you can cut this sequence at some point with islice(seq, count) function from the same module. Commented May 10, 2018 at 14:09

2 Answers 2

13

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.

Sign up to request clarification or add additional context in comments.

1 Comment

what about abc[18:20]? :P
1

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'

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.