0

I want to reverse an array 'ar' by using another array 'br' but it gives an IndexError! I don't know why can you help please !

# Reversing array
from array import*

ar = array('i', [1, 2, 3, 4, 5])
br = array('i',[])

d = len(ar)-1
print(d)
for i in ar:
    br[d] = i
    d = d-1
print(br)
Icewizard
  • 39
  • 2
  • 1
    you better use python `list` instead of array, you get indexerror cause `br` is empty and does not have `[d]` index, you need to append the value to the list/array rather than to assign by index – PYPL Aug 31 '20 at 11:14
  • 1
    @PYPL How would using a list help? – deceze Aug 31 '20 at 11:15
  • ok but can you tell me why it gives indexerror please – Icewizard Aug 31 '20 at 11:18
  • @Icewizard they did tell you, because `br` is empty, and you try to use indexed assignment, `br[d] = i`, no matter the value of `d`, it will always raise an `IndexError`, and in general, if you index passed the size of the array, it will raise an IndexError. That's *what an index error means* – juanpa.arrivillaga Aug 31 '20 at 11:19
  • Thanks for resolving doubts ! – Icewizard Aug 31 '20 at 11:36

1 Answers1

2

Array br is empty so you need to do br.append(i) instead of br[d] = i. Note that the array can be reversed with reverse.

idetyp
  • 486
  • 1
  • 3
  • 13