Kodeclik Blog

What does [-1] mean in Python?

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.
To learn more about lists and indices, see our blogpost on arrays vs lists in Python.
If you enjoyed this blogpost about negative indices in lists, learn negative indices in Python strings.
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!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2024. All rights reserved.