Mastering Negative Indexing in Python

Victor Oketch Sabare
1 min readJan 13, 2023

--

Photo by Farzad on Unsplash

In Python, we have two indexing systems for lists:

  • Positive indexing: the first element has the index number 0, the second element has the index number 1, and so on.
  • Negative indexing: the last element has the index number -1, the second to last element has the index number -2, and so on.

In practice, we almost always use positive indexing to retrieve list elements. Negative indexing is useful when we want to select the last element of a list — especially if the list is long, and we can’t find the length by counting.

row_1 = ['Facebook', 0.0, 'USD', 2974676, 3.5]

print(row_1[-1])
print(row_1[4])
Output
3.5
3.5

Notice that if we use an index number that is outside the range of the two indexing systems, we’ll get an IndexError.

row_1 = ['Facebook', 0.0, 'USD', 2974676, 3.5]
print(row_1[6])
Output
IndexError: list index out of range

--

--

Victor Oketch Sabare
Victor Oketch Sabare

Written by Victor Oketch Sabare

Data Geek passionate about Data Science, Data Engineering and Artificial Intelligence. Keen on using data to drive business insights and improve efficiency.

No responses yet