I am a beginner in Python. I am trying to solve the following problem using modulo function but I'm facing
error: list index out of range.
Problem: Given an array of integers arr[]
of size N and an integer, the task is to rotate the array elements to the left by d
positions.
Code:
def rotate(arr, d):
temp= []
n = len(arr)
for i in range(n):
temp[i]=temp[(i d)%n]
return temp
CodePudding user response:
At this part of code temp[(i d)%n]
, you are trying to access an element of a list that is empty. Because of this, your program produces that error. You probably meant to write arr[(i d)%n]
instead.
Also, when you write temp[i]
, Python expects your list to be longer than i
.
Instead of this, you can use temp.append(element)
to add an element at end of the list.
After these changes, your function should look like this.
def rotate(arr, d):
temp = []
n = len(arr)
for i in range(n):
temp.append(arr[(i d)%n])
return temp