0

I wrote a python program to split the array and add the first part to the end, but the programs throws an error as below

Traceback (most recent call last):
  File "<string>", line 13, in <module>
File "<string>", line 5, in splitArr
IndexError: list index out of range

The code is below

def splitArr(arr, n, k): 
    for i in range(0, k): 
        x = arr[0]
        for j in range(0, n):
            arr[j] = arr[j + 1]
          
        arr[n-1] = x
          
arr = [12, 10, 5, 6, 52, 36]
n = len(arr)
position = 1
  
splitArr(arr, n, position)
  
for i in range(0, n): 
    print(arr[i])

I don't know what I have done wrong. Please help me.

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
  • I changed the `n` in your `for j in range(0,n):` line to `n-1` and the program now runs fine, however I'm unsure of if this is how you intended for the program to work. Please verify. – 4RJ Jun 17 '21 at 15:30
  • Try to say in your question what are you trying to do to receive more useful answers. – Pau Arlandis Martinez Jun 17 '21 at 21:55

2 Answers2

1

You can slice a list like this : arr[start:stop:end]

See Understanding slice notation

arr = [12, 10, 5, 6, 52, 36]
position = 1
new_arr = arr[position:]+arr[:position]
print(new_arr)

[10, 5, 6, 52, 36, 12]
DGMaxime
  • 21
  • 1
  • 3
  • While code-only answers might answer the question, you could significantly improve the quality of your answer by providing context for your code, a reason for why this code works, and some references to documentation for further reading. From [answer]: _"Brevity is acceptable, but fuller explanations are better."_ – Pranav Hosangadi Jun 17 '21 at 15:34
1

The error you are facing is due to list index out of range.

I have modified the range in "j" for loop from "for j in range(0, n)" to "for j in range(0, n-1)" in your code and it is completely working.

The code:

def splitArr(arr, n, k): 
    for i in range(0, k): 
        x = arr[0]
        for j in range(0, n-1):
            arr[j] = arr[j + 1]
          
        arr[n-1] = x
          
arr = [12, 10, 5, 6, 52, 36]
n = len(arr)
position = 1
  
splitArr(arr, n, position)
  
for i in range(0, n): 
    print(arr[i])
Vijayaragavan K
  • 319
  • 1
  • 5