'How to replace some elements in a list? Python

I'm working on a cryptology program that uses some of triangular numbers to encrypt a number. My aim is: If the number in "triangularNumbers" list is included to the sum appending 1 to the encryptedKey list, unless it is included appending 0. If the element is (00), it means the list has ended and we start to go at opposite direction. Working principle is similar to knight rider lights! Unfortunately, I suffer from problems about appending 1s and 0s. You can find the code below:

triangularNumbers=[1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66]
index1=[]
encryptedKey=[]

def DigitTheKey(key):
    global num1
    global num2
    global num3

    num1=key//10000
    num2=(key%10000)//100
    num3=key%100

    return num1
    return num2
    return num3

keyNo=int(input("Please enter the key:\t"))

DigitTheKey(keyNo)

while(num1!=0):

    for i in range(10,-1,-1):
        if triangularNumbers[i]<=num1:
            index1.append(i)
            num1-=triangularNumbers[i]
            i-=1

    if num1!=0:
        index1.append("(00)")
    
        for i in range(0,11,1):
            if triangularNumbers[i]<=num1:
                index1.append(i)
                num1-=triangularNumbers[i]
                i+=1

#Problem occurs with the while loop below
a=0
while a<=len(index1):

    for i in range(10,-1,-1):
        print("\nindex1[a]={}\na={}\n".format(index1[a],a))
        if index1[a]==i:
            encryptedKey.append(1)
            a+=1
        
        else:
            encryptedKey.append(0)


    
    encryptedKey.append("(00)")
    a+=1

    for i in range(0,11,1):
        if a>len(index1):
            break
    
        elif index1[a]==i:
           encryptedKey.append(1)
           a+=1
       
        else:
            encryptedKey.append(0)

#Problem occurs with the while loop above
    

encryptedKey.append("(00)")
encryptedKey=encryptedKey.pop()
print("Encrypted Key:\t{}".format(encryptedKey))

Also, here is the error message:

    elif index1[a]==i:
IndexError: list index out of range

From now, thank you very much!



Solution 1:[1]

if a>len(index1):

This here is your problem. len(index) is already one higher than you largest index i.e. a=[0,1,2,3], len(a)=4, a[3]=3 and a[4] -> IndexError: list index out of range. So instead of > you will have to use >= to catch that case.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Eumel