Get python list index out of range

Question:

I’m trying to create over flowing pythonic list meaning that if i’m trying to get the index of list even if the index is larger then then the list size.

if the index is bigger then the list size I want to get the index from the start of the list.

for example if the list size is 5

l = [1,2,3,4,5] 

so l[7] should return 3 [index 2]

Thanks!

Asked By: Alon Barad

||

Answers:

Your question is not clear:

suppose:

l = [1,2,3,4,5]

l[0] is 1
l[1] is 2
and so on...

You can do a forloop to print all the values:

for x in range(len(l)):
   print(l[x])

Now if you want to plug in large values in x you can use mod operator %

l[x%len(l)]

here x can be any large number.

when x=7:

l[7%len(l)]
#output
3

when x=5:

l[5%len(l)]
#output
1
Answered By: God Is One

You’ll want to use the % (modulo) operator to handle this type of situation, and I’ll assume that you meant l[7] should return 3 (at index 2 in the list). A functional solution:

def overflow_index(l, idx):
    return l[idx % len(l)]

L = [1, 2, 3, 4, 5]
print(overflow_index(L, 7))  # Output: 3

An object-oriented solution, defining subclass of list and overriding its __getitem__ method which handles subscript access, i.e. l[7]:

class OverflowList(list):
    def __getitem__(self, idx):
        return super().__getitem__(idx % len(self))


OL = OverflowList([1, 2, 3, 4, 5])
print(OL[7])  # Output: 3

The super().__getitem__ function refers to the builtin list‘s method, which needs to be called to prevent infinite recursion.

Answered By: Ian Sharff
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.