What Are The Meaning of “a[-1]” and “a[::-1]” in Python?

Python provides a lot of different syntax and usages which may seem very confusing sometimes. The a[::-1] or [::-1] are some of them. First of all the [] is used to specify single or more items in a List. There are different ways to specify single or multiple items by using square brackets.

List Syntax

We can access the list items by using the [] signs where different specifiers are put between square brackets. The syntax of the square brackets is like below.

  • START is the start index number
  • STOP is the end index number
  • STEP is optional and used to specify the increment of the selection. By default if the STEP is not specified it is assumed as 1 .

a[-1] Usage

Python lists can use negative indexes in order to select in reverse order. The negative index means starting from the end of the list. Where [-1] first item from the last. In the following example, we will select the last item by using a[-1] .



a[::-1] Usage

The a[::-1] may seem very similar to the a[-1] but there is a difference. If we take a look to the syntax of the list we can see that we can provide 3 parameters by separating them with double colon. The first two parameters are provided as empty which are start and stop parameters. If we do not provide start and stop parameters all list items are returned. The last parameter is step which is provided as -1. This means step back from the last item to the first item. As a result the list is returned in reverse order by using a[::-1] .



We can see that the output is the reverse order of the specified list.

[4, 3, 2, 1]

Leave a Comment