Reputation: 484
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'
.
Upvotes: 5
Views: 1701
Reputation: 3706
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'
Upvotes: 1
Reputation: 362577
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.
Upvotes: 13