Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop in a list more times that list size in python?

Tags:

python

loops

list

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!

like image 819
Emmanuel Arias Avatar asked Apr 26 '18 01:04

Emmanuel Arias


People also ask

How do you repeat a list multiple times in Python?

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

How do you iterate over a list length?

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.

How do you make a list loop in Python?

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.


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

like image 184
wim Avatar answered Nov 03 '22 00:11

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'
like image 45
f5r5e5d Avatar answered Nov 03 '22 00:11

f5r5e5d