Can't seem to understand why i get index out of range exception here

code:

values = [16, 1, 7, 2, 19, 12, 5, 20, 2, 10, 17, 14, 1, 9]

#0   1   2   3   4   5   6   7   8   9   10  11  12  13
#-14 -13 -12 -11 -10 -9  -8  -7  -6  -5  -4  -3  -2  -1

# Write your answer below

reversed_values = []

for i in range(len(values)):
    
    reversed_values[i] = values[-i-1]

exception:

IndexError                                Traceback (most recent call last)
<ipython-input-1-2f011a35293c> in <module>
     10 for i in range(len(values)):
     11 
---> 12     reversed_values[i] = values[-i-1]

IndexError: list assignment index out of range
1 Like

You are trying to assign values to empty list reversed_values that raise IndexError: list assignment index out of range exception.

You can use append method of list to add new item

values = [16, 1, 7, 2, 19, 12, 5, 20, 2, 10, 17, 14, 1, 9]

reversed_values = []
for i in range(len(values)):
    reversed_values.append(values[-i-1])

Or You can initialize list with zeros and then use your code as it is

reversed_values = [0] * len(values)   # Equivalent to [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

for i in range(len(values)):
    reversed_values[i] = values[-i-1]
2 Likes

Agree.
Need append if reversed_values is an empty list.

An alternative way with numpy:

import numpy as np
reversed_values = np.zeros(shape=(len(values),))

for i in range(len(values)):
    
    reversed_values[i]+= values[-i-1]

Note the shortcut (dunno if explained in the course):

values[::-1]

Output:

[9, 1, 14, 17, 10, 2, 20, 5, 12, 19, 2, 7, 1, 16]