Python lists are sequential collections of entities. They are iterable, meaning you can explore them sequentially by requesting one element at a time from the list. They are also random access, meaning you can request specific elements by specifying the location of the element.
Below is a simple Python list of numbers:
The output will be:
If you would like to print just the first element, you use index 0 (recall that indices begin from zero). If you would like to use the last element, we use index 5 (because this particular list has 6 elements).
The output is:
The [-1] index in Python
As you can see above it can feel a bit inconvenient to print the last element because it requires you to first know the length of the list (and then subtract 1). You can do it by:
The output will still be:
The “-1” index is really shorthand for what is going on in the second print statement. This means you can shorten the above expression to:
The output again is:
In other words, -1 is the index of the last element. Similarly, -2 is the index of the second-to-last element.
The output is:
We can continue this all the way to do:
The output will be:
Again, the last index is a bit awkward. So you can replace it as follows:
yielding the same output as above.
To summarize, the index -1 is really the last element. Similarly, the index 0 is the first element. You can count forwards from zero and increment the index one by one (yielding positive numbers). Similarly, you can count backwards from -1 and decrement the index by one each step of the way (yielding more negative numbers). Just think of this as convenient ways to iterate over the list, either first-to-last or last-to-first.
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.