Intellipaat Back

Explore Courses Blog Tutorials Interview Questions

Explore Tech Questions and Answers

Welcome to Intellipaat Community. Get your technical queries answered by top developers!

0 votes
2 views
by (19.9k points)

I am trying to execute the following python code:

def construct(s, k, a):

    index = 0

    # Finding the index which is not -1

    for i in range(s):

        if (a[i]!=-1):

            index = i

            break

    # Calculating the values of the indexes index-1 to 0

    for i in range(index-1, -1, -1):

        if (a[i]==-1):

            a[i]=(a[i + 1]-1 + k)% k

    # Calculating the values of the indexes index + 1 to n

    for i in range(index + 1, s):

        if(a[i]==-1):

            a[i]=(a[i-1]+1)% k

            print(a)

# Driver code

s, k = 6, 7

a = [1, 2, 3, 4, 5]

construct(s, k, a)

I get the following error:

IndexError: list index out of range

1 Answer

0 votes
by (25.1k points)

IndexError occurs when the list index is out of range, you need to make sure that your code is not accessing list index that is not valid.

If you want to get a deeper understanding of python you can watch this youtube video: 

Browse Categories

...