I need to know if in python exist a function or native lib that allow 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 a parameter with value 10, the result is 'a'. If the parameter with value 18 is 'd'.
Thanks!
Regards!
Using the * Operator The * operator can also be used to repeat elements of a list. When we multiply a list with any number using the * operator, it repeats the elements of the given list. Here, we just have to keep in mind that to repeat the elements n times, we will have to multiply the list by (n+1).
You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.
Using for Loops You can use a for loop to create a list of elements in three steps: Instantiate an empty list. Loop over an iterable or range of elements. Append each element to the end of the list.
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With