Reversing a list(practice problem)

Hi can anyone give me clarity what does values[-i -1] is saying? Thank you.

Screen Link:
https://app.dataquest.io/m/1009/lists-and-for-loops-practice-problems/6/reversing-a-list

My Code:

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

Hi @uditchauhan

You are given the list

values = [ 16, 1, 7, 2, 19, 12, 5, 20, 2, 10, 17, 14, 1, 9]
# index:   0  1  2  3  4  5  6  7  8  9   10  11  12  13  14
#position: 1  2  3  4  5  6  7  8  9  10  11  12  13  14  15

In the forward order, i starts from 0 and will count out to the length of the list, in this case the 15th position (that is the 0th up to the 14th index). - i - 1 starts instead from the from the back of the list -0 -1 = -1 (recall i is 0 at the start of the loop). Also recall that python is zero-indexed hence the index and positions are different from every individual element in the list.

Hope this helps!

thanks @masterryan.prof. So it will go on like -1,-2,-3… till the loop concludes right?

In addition to what @masterryan.prof has said, kindly view the code below. It is the one of the quickest ways to reverse a list:

reversed_values = values[::-1] 
1 Like

thank you @monorienaghogho for the tip. Does the syntax has a specific meaning [: : -1]?

[::1] means take every item on the list one after the other. Until the end.

[::-1] means take every item on the list starting from the ending. Remember that the last item on a list is indexed as -1. So it counts -1, -2, -3, ... until it gets to the first item.

1 Like

Great , thanks a lot

1 Like

Yes @uditchauhan: just think of the logic as the loop continues. Note that what @monorienaghogho said does not work in this case because the loop will repeat and print the list i times, so you need to remove the loop for his method to work.

i.e.

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

# Write your answer below
reversed_values = values[::-1]

print(reversed_values)

image

1 Like