Issue with reversing the records in the list by a for loop and hard coding

Screen Link:

My Code:
What I expected to happen:
Why the for loop does not throw out of index error though we are adding records to reversed_values from “last to beginning” order.

What actually happened:

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

# Write your answer below

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

This code is successful.

However the following one throws the out of index error:

reversed_values[-1] = 9

Please help me understand the issue.

When do you run this line of code?

If you are running it after your for loop has finished running, then it shouldn’t throw any error.

Given your current code, the only reason you would get an out of index error is if reversed_values is empty when you run the above line of code. Because as long as the list has even a single value stored in it, you won’t get an out of index error.

So, there is probably more context to your code than you have currently shared.

I would suggest looking into where you are adding your line of code and when you are running it to try and resolve the error.

Sorry for the bad explanation of the issue.

The following code is successful:
values = [16, 1, 7, 2, 19, 12, 5, 20, 2, 10, 17, 14, 1, 9]

Write your answer below

reversed_values =

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

My question is, reversed_values is an empty list.
When the loop is executed, the records are being added to the list from last to first. As reversed_values is an empty list, how can the loop add record to the last index of an empty string?

The for loop is defined to iterate in the reverse order - from len(values) to 0.

So, the items from values are indexed starting from the last item. But the list, reversed_values gets updated normally. You are not appending an item to reversed_values starting from the end of reversed_values. You take the last item from values, append it to reversed_values, then in the next iteration you take the second last item from values, append it to reversed_values and so on.

In your for loop, print out i and values[i-1] for each iteration and you will see what happens at each step.