Home > Software engineering >  IndexError when reversing an array in Python 3
IndexError when reversing an array in Python 3

Time:07-09

I tried to reverse an array in Python, but I got an IndexError: list index out of range. Can anyone help me find out what's my problem?

Here's my code:

def reverseArray(a,n):
    b = []
    
    for i in range(n   1):
        b.insert(0, a[i])
    
    return b

Error:

Traceback (most recent call last):
  File "/tmp/submission/20220709/03/24/hackerrank-6dc9d7d54d580ec91f519f2a6455587b/code/Solution.py", line 33, in <module>
    res = reverseArray(arr,arr_count)
  File "/tmp/submission/20220709/03/24/hackerrank-6dc9d7d54d580ec91f519f2a6455587b/code/Solution.py", line 21, in reverseArray
    b.insert(0, a[i])
IndexError: list index out of range

CodePudding user response:

Since reverseArray is the call which caused the issue, let's fix it first

Refactoring your code we get :

def reverseArray(a, n):  # rather unpythonic
    b = []
    for i in range(n - 1, -1, -1):
        b.append(a[i])
    return b

Which works like this taking two arguments :

>>> foo = [1, 2, 3]      
>>> reverseArray(foo, 3)
[3, 2, 1]

But that is unpythonic and can be alot better, something like this :

def reversed_array(a):
    return [*reversed(a)]

Which is exactly the same thing except it takes one less argument of length
Example use :

>>> foo = [1, 2, 3]
>>> reversed_array(foo) 
[3, 2, 1]

CodePudding user response:

Since the list "b" doesn't contain any element , so b.insert(0,a[i]) won't work . What you have to do instead is , use b.append(a[i]) , which in your case , will get the job done.

CodePudding user response:

If you are using it like this:

reverseArray([], 0)
reverseArray([1, 2, 3], 3)

The actually problem is:

range(n   1)

Cause range creates sequence from 0 to n - 1:

range(0) # empty seq
range(3) # 0, 1, 2

So you simply need do it like this:

def reverseArray(a: list, n: int):
    b = []
    
    for i in range(n): 
        b.insert(0, a[i])
    
    return b

But there is shorter, faster and more pythonic way to do it:

a = [1, 2, 3]
reversed_a = a[::-1]
>>> reversed_a
[3, 2, 1]

CodePudding user response:

Actually there's a quick and "pythonic" way to reverse an array in Python. You can use the Array Slicing. Put a pair of brackets after your array just like calling an element. For example, list1 = [1, 2, 3, 4, 5, 6]. You can use the array slicing to reverse it like this: list = list[::-1]. This is a very use ful skill in Python, and it's capable for all iterable items. For more informations about slicing in Python, see here.

Array slicing is just a simple way to reverse. Now let's get back to our question. The goal is to reverse the given array. Instead of the normal hard way, we can think the problem reversely. In your original code you were enumerating the array from start to end, which is a hard way to control the index of the array. Now let's enumerate it from back to start. So for i in range(n 1) can be replaced with for i in range(n - 1, -1, -1). This line of code enumerates from -1 to 0. Inside the for-loop, you can directly add a[i] in b (Because is in reverse order). After that, the code for this method will be:

def reverse_array(array):    # Follow PEP8!
    res_array = []
    for i in range(len(array) - 1, -1, -1):
        res_array.append(array[i])
    return res_array

And here's an example:

>>> example = [1, 2, 3, 4, 5, 6]
>>> reverse_array(example, 6)
[6, 5, 4, 3, 2, 1]
  • Related