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

  • A+
Category:Languages

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!


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: