Dark Header
Dark Header

Reputation: 1

I am getting Error : list assignment index out of range

def encryptRailFence(text,key):
    a=text
    b=[]
    for i in range(key):
        if i % 2 == 0:
            b.append(a[i])
        else:
            b[i]=a[i]
        i += 1
    print(b)

encryptRailFence('Vijay',2)

The below function throws error list assignment index out of range. I am not able to figure out the cause of the error

Upvotes: 0

Views: 29

Answers (1)

Deepak Patankar
Deepak Patankar

Reputation: 3302

Take a example:

  1. When i is 0, you are appending one element to the list b.
  2. When i is 1, you are using b[1] = a[1],but the size of b is 1 and you cannot access b[1], that's why you are getting index out of range error.

The line i+=1 won't change the value of i used in the iteration. For reference see link

Upvotes: 1

Related Questions