What Are Negative Indexes In Python?

What Are Negative Indexes In Python?

Published on October 07 2023

In this tutorial, we will learn what are negative indexes in Python and their benefits with an example. This tutorial is part of Python's top 25 most commonly asked interview questions.

Definition

  • The sequences in Python are indexed.
  • The index usually starts from 0, i.e., the first element has an index of 0, the second has 1, and so on.
  • The index for the negative number starts from '-1' i.e. last element, the second last element has an index of ‘−2’, and so on.
  • Arr[-1] means the last element of the array Arr[].
  • Negative indexes are the indexes from the end of the list or tuple or string.

Example

arr = [1, 2, 3, 4, 5, 6]

# get the last element
print(arr[-1]) 

# Output 
6

# reverse the entire list
print(arr[::-1])

# Output
[6, 5, 4, 3, 2, 1]

To know about it, please refer to the official documentation website - official website.