Skip to content Skip to sidebar Skip to footer

Python Make A Circular List To Get Out Of Range Index

I'm looking for ways to make a list into circular list so that I can call a number with index out of range. For example, I currently have this class: class myClass(list): definit

Solution 1:

If you insist on creating an entire class for this, subclass UserList, implement __getitem__ and use the modulo operator (%) with the length of the list:

classmyClass(UserList):
    def__getitem__(self, item):
        returnsuper().__getitem__(item % len(self))

myList = myClass([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(myList[12])

outputs

3

Depending on your usage, it's possible you'll need to implement several other list methods.

CAVEAT: Be careful to not loop over myList. That will create an infinite loop because __getitem__ will always be able to provide an element from the list.

Post a Comment for "Python Make A Circular List To Get Out Of Range Index"