Reverse a list with range and negative indexing

I have a question around a particular lists and for loops practice exercise. The project goal is Define a reversed_values variable whose values are the values in the values list, but in reversed order. I’ve pasted the code below:

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

# Write your answer below
reversed_values = []
count = []
for i in range(len(values)):
    reversed_values.append(values[-i - 1])
    count.append(i)

My question is, how come when specifying the assigning index for reversed_values, do you have to input [-i - 1]? I’m aware that stating -i indicates start backwards from the range object, but the last range object is 13, so wouldn’t the index used for the first append/assignment be 13? Essentially how come we have to specify the [-i -1] instead of [-i]?

That’s because of the following -

range(len(values))

range(), when defined as above, starts the value from a 0. The range is from 0 to len(values)-1. So, when you have

values[-i - 1]

for your first i, that will be the equivalent of values[-1]. If you remove that -1, you will start at values[-0] which is the same as values[0] which would be the item at index 0, and not the last index.

An alternative way for this is to define the range() as -

range(1, len(values) + 1)

Then you can use values[-i], because your range would be from 1 to len(values) in this case.

There is one more way you can approach this by modifying range(), but I will leave that for you to explore :wink:

2 Likes

In addition to what the doctor has said. Forward indexing starts from 0 and ends at n-1. However, backward indexing starts at -1 and ends at -n because you cannot have an index of -0.

1 Like

Thank you! It was funny because I figured it out right before reading your answer. I was getting lost because if I printed out i for i in range(len(values)), it was displaying 0 through 13, however simply printing range(len(values)), showed me the object actually counts to 14, hence the -1 because the length is actually 14 items, and indexing starts at 0 not 1. Thanks for your answer @monorienaghogho this speaks to exactly what I discovered!

Thank you!

2 Likes

@the_doctor

Brilliant, thank you for your explanation.
The one thing I still cannot understand is why there is no separator between -i and -1 in values[-i -1]. This is the only occurence, that I know of, where a list has two items without any ‘,’ or ‘:’ between them.

Is there any reason for that?

thank you

It’s just normal arithmetic.

-i - 1 is 1 subtracted from -i. You can use basic arithmetic operations for indexing/slicing.

I didn’t know you could use basic operations for slicing/indexing.

thanks, now it makes sense.