-1

I have a list of items:

items = [a, b, c, d]

I need it to be so that if I say items[4] which isn't in the list, the returned element should be the first element only, which is a, like a loop, instead of a IndexError: index out of range error.

PradMaster
  • 83
  • 10
  • 1
    Does this answer your question? [Wrapping around on a list when list index is out of range](https://stackoverflow.com/questions/22122623/wrapping-around-on-a-list-when-list-index-is-out-of-range) – mkrieger1 Dec 19 '20 at 09:38

2 Answers2

2

You can employ operator %:

def getItem(items, index):
    return items[index % len(items)]

items = [‘a’, ‘b’, ‘c’, ‘d’]
print(getItem(items, 42))

Output:

c
quamrana
  • 37,849
  • 12
  • 53
  • 71
0

To avoid the error message, you can handle it as an exception for the indexes not in array's range. i.e. if the index entered is n then

try:
    print(items[n])
except:
    print(items[n % len(items)])

I hope this helped..!

DNShah
  • 46
  • 3