python-3.xlistloopsindex-error

IndexError: list index out of range - looping a list


I have created a list with 26 items.

alphabet = ['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']

I wish to use shift the letter to next selected position: i.e. "hello" to shift by position 5 and return me text as "mjqqt"

For which I have used the "for loop", and it works fine too until I use a letter z as it is the last item in the list.

Is there a way to loop the list once it has reached the alphabet[25] to restart to position alphabet[0], which means when the shift letter is "z" and shift by position 5 I want it to start again from position 0 to return "e"

I have created a function which for loop to shift each letter in the word and return the encrypted cipher_text.

def encrypt(plain_text, shift_amount):
    cipher_text = ""
    for letter in plain_text:
        position = alphabet.index(letter)
        new_position = position + shift_amount
        cipher_text += alphabet[new_position]
    print(f"The encoded text is {cipher_text}")
encrypt(plain_text=text, shift_amount=shift)

error: Traceback (most recent call last): File "\caesar-cipher\caesar-cipher-4 Final.py", line 36, in encrypt(plain_text=text, shift_amount=shift)

IndexError: list index out of range


Solution

  • Pretty sure you can do that with modulo:

    def encrypt(plain_text, shift_amount):
    cipher_text = ""
    for letter in plain_text:
        position = alphabet.index(letter)
        new_position = (position + shift_amount) % len(alphabet)
        cipher_text += alphabet[new_position]
    print(f"The encoded text is {cipher_text}")
    

    This should work as you expect, you just loop the index if it is past the length of your alphabet