Python - how to count an index of a list continuously without using libraries?

Viewed 424

Below I have a List of the lowercase alphabet. My task is to get the index of a lowercase letter from the list and add the shift. The shift can vary and be other than 1000. It could also be 50000 or 10 etc. If the index + shift is larger than 25, it should continue counting from "a" until (index + shift) has been reached and return the letter. I am not allowed to use libraries.

My solution doesn't work for big shifts like 1000

shift = 1000
alphaList = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']

index = alphaList.index('u')
index = (index + shift) - len(alphaList)   # this part has to be adjusted 
print(index)
print(alphaList[index])

Result should be: 'g'

what I get is:

---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-20-8d37e597ee25> in <module>
      5 index = (index + shift) - len(alphaList)
      6 print(index)
----> 7 print(alphaList[index])

IndexError: list index out of range
----------------------------------------------------------------------------
2 Answers

You are looking for the modulo operator. From the documentation (emphasis is mine):

The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand

index = (index + shift) % len(alphaList) 

Use the modulus operator instead here:

index = (index+shift) % len(alphaList) 
Related