Hey @marctare,
Iām new to Code Academy but have done some coding before, and part of your question revolves around an idea that I learned very early on in programming - so I hope this helps!
I think your only problem is how youāre thinking about the syntax of that last line.
You said, "...canāt understand why I get syntax errors if I donāt have the '-' character, which Iām assuming is a negative indices since itās bringing up 'orange' when printed."
And this is actually NOT true!
Letās say you have a list,
list_one = ['cat', 'dog', 'penguin', 'beaver', 'squirrel']
list_one
would have elements 1 through 5 (which would be cat, dog, penguin, beaver, squirrel) and would have indices 0 through 4 (ācatā would be index 0, ādogā would be index 1, etcā¦)
It is commonly stated that the length of a list would be n
.
This is because the number of items in a list is the exact same value as the length of a list. (So n is literally just the number of elements in the list and, therefore, the length.)
Here, list_one
has 5 items in it, so itās length would be 5.
However, we have learned through the Python 3 course that indices start at 0 instead of 1. This would mean that the last index of a list would be the value (length of the list)-1
.
When looking at list_one
, I stated before that the length of the list is 5 but the number of indices of the list is 4 (due to the first index being 0).
The expression (length of the list) - 1
in this case would be equivalent to 5 - 1
which would equal 4, our number of total indices in the list!
So as you can see, the statement print(colors[len(colors) - 1])
does not contain anything regarding negative indices, but it actually just subtraction!
In the example in this thread, the goal is to get the last element/item of a list.
If you donāt know how many elements are in a list but still want to access the last one OR if you want to find the last element of a list without using the len() function, then all you would have to do is name_of_list[len(name_of_list)-1])
because it will give you the last element of the list by subtracting 1 from the total length of the list, which would in turn give you the value of the index of that last element.
Then when you print, you can see the element thatās located in that index, which would be the one in the last spot of the list!