Why do we use negative numbers in a list?

¡Hi! :hugs: I was checking out the video walkthrough of this exercise but I read some code that confused me a bit.
These instructions are for spacing the different elements in a string accurately, so that a comma is written in between each of the elements of the list and a dot when the last element of the list has come. The string is the following, where traveler[0] is the name of the traveler and traveler[2] is their destination:

interests_string = "Hi " + traveler[0] + ", we think you'll like these places around " + traveler[2] + ":"

And the part I don’t understand is the following: why does traveler_attractions[-1] have that “[-1]”? I thought lists elements go from 0 onwards so why use negative numbers?

for i in range(len(traveler_attractions)):
  if traveler_attractions[-1] == traveler_attractions[i]:
    interest_string += "the " + traveler attractions[i] + "."

  else:
    interest_string += "the " + traveler attractions[i] + ", "

Thanks! :smile: (By the way, this code appears in the walkthrough at 1:13:46)

https://www.codecademy.com/paths/computer-science/tracks/cspath-cumulative-tourism/modules/cspath-boredless-tourist/projects/the-boredless-tourist

You can start from the back with negative indices

2 Likes

There are two ways of traversing a list:

  • left to right
  • right to left

The index from left to right begins with zero, and continues upward in count.

The index from right to left begins with negative 1 and continues leftward down the number line from there.

Why -1? Because zero is already taken.

Now consider that in a zero-indexed list, the last element can be found using,

x[len(x) - 1]

The second last index would be,

x[len(x) - 2]

and so on.

In other words, negative indices simply remove the redundant call to the len() function.

x[-1], x[-2], ...
6 Likes

Thanks @fight_dragons and @mtf , I think I got it but just to make sure XD. You mean that if the list has for example three elements, numbered 0-1-2, using [-1] would be the same as using [2]? And for example if I use [-2] that would be like using [1] in this example, right?

3 Likes

That is exactly right :100:

3 Likes