How to Use Python Array Index -1?

In this tutorial, I will explain how to use the Python array index -1 in detail with examples. In a recent Python webinar, array index -1 was the topic of the discussion. We will use index -1 to fetch the last element of the given collection without knowing the length of the collection. Let us learn more about this topic.

What is Negative Indexing in Python?

Negative indexing is useful in Python lists. It will allow you to access elements from the end of the list. While positive indices start from 0, negative indices start from -1, where -1 refers to the last element of the collection, -2 to the second last, and so on.

For example, consider the following list of popular US cities:

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]

Using negative indexing, you can access the elements as follows:

  • cities[-1] returns “Phoenix”
  • cities[-2] returns “Houston”
  • cities[-3] returns “Chicago”

Read setting an array element with a sequence error in Python

Python Array Index -1 Examples

We use negative indexing when we need to access the last few elements of a list without knowing its length.

Let us see some practical examples of how negative indexing can be applied in Python through some real scenarios.

Example 1: Accessing the Last Element

Consider you have a list of top universities in the USA, and you want to fetch the last university in the list:

universities = ["Harvard", "Stanford", "MIT", "Caltech", "Princeton"]
print(universities[-1])

Output:

Princeton

You can see the executed example code in the below screenshot.

Use Python Array Index -1 Accessing the Last Element

In this example, universities[-1] return “Princeton”, the last element in the list.

Check out How to Get Values from a JSON Array in Python?

Example 2: Slicing with Negative Indices

Negative indexing can also be used in slicing operations to create sublists. If you want to get the last three universities from the list, you can use negative indices in the slice.

universities = ["Harvard", "Stanford", "MIT", "Caltech", "Princeton"]
last_three_universities = universities[-3:]
print(last_three_universities)

Output:

['MIT', 'Caltech', 'Princeton']

Let us have a look at the screenshot below to know more.

Use Python Array Index -1 Slicing with Negative Indices

In this example, universities[-3:] return a sublist containing the last three universities.

Read How to Sort an Array in Python?

Example 3: Removing the Last Element

Sometimes, you may need to remove the last element from a Python list. For this, you can use negative indexing like the below:

states = ["California", "Texas", "Florida", "New York", "Illinois"]
removed_state = states.pop(-1)
print(removed_state)
print(states)

Output:

Illinois
['California', 'Texas', 'Florida', 'New York']

Go through the screenshot below for the reference.

Use Python Array Index -1 Removing the Last Element

Here, states.pop(-1) removes and returns the last element, “Illinois”, leaving the list with the remaining states.

Example 4: Reversing a List

Negative indexing can be leveraged to reverse a list using slicing. This is useful when you need to process elements in reverse order.

presidents = ["Washington", "Adams", "Jefferson", "Madison", "Monroe"]
reversed_presidents = presidents[::-1]
print(reversed_presidents)

Output:

['Monroe', 'Madison', 'Jefferson', 'Adams', 'Washington']
Use Python Array Index -1 Reversing a List

In this example, presidents[::-1] create a new list with elements in reverse order.

Example 5: Processing Recent Data

Think that you are working with a list of recent stock prices for a company based in the USA, and you want to analyze last week’s data.

stock_prices = [150, 152, 153, 155, 157, 160, 162, 165, 167, 170]
last_week_prices = stock_prices[-7:]
print(last_week_prices)

Output:

[155, 157, 160, 162, 165, 167, 170]

Here, stock_prices[-7:] extracts the prices from the last seven days.

Check out How to Convert an Array to a Tuple in Python?

Example 6: Handling User Input

Suppose you have a list of user inputs, and you want to validate the most recent input; then you can write the code like below:

user_inputs = ["John", "Doe", "john.doe@example.com", "New York", "NY", "10001"]
latest_input = user_inputs[-1]
print(latest_input)

Output:

10001

In this case, user_inputs[-1] retrieves the most recent input.

Check out Python program to print the smallest element in an array

Common Issues and How to Avoid Them

Now, let me show you some common issues that you might receive and how to fix them.

Issue 1: Index Out of Range

If you try to access an index that doesn’t exist, Python will raise an IndexError.

states = ["California", "Texas", "Florida"]
print(states[-4])

Output:

IndexError: list index out of range

To avoid this, ensure your index is within the valid range of the list.

Issue 2: Modifying Lists While Iterating

Modifying a list while iterating it using negative indices can lead to unexpected behavior.

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
for i in range(len(cities)):
    if cities[-1] == "Phoenix":
        cities.pop(-1)
print(cities)

Output:

['New York', 'Los Angeles', 'Chicago', 'Houston']

Here, the loop may not behave as expected if the list size changes during iteration. To avoid this, consider creating a copy of the list or using list comprehensions.

Check out How to Print Duplicate Elements in Array in Python

Best Practices for Using Negative Indexing in Python

To use the negative indexing efficiency, consider the following best practices:

Use Clear and Descriptive Variable Names

The name of the variables should clearly describe their purpose so that it will be easier to understand.

recent_temps = temperatures[-7:]

Combine Positive and Negative Indexing

Combining positive and negative indexing makes code understandable.

data = ["A", "B", "C", "D", "E"]
middle_elements = data[1:-1]
print(middle_elements)

Output:

['B', 'C', 'D']

Document Your Code

Add comments to explain why you’re using negative indexing.

# Extract the last three elements for analysis
last_three_elements = data[-3:]

Conclusion

In this tutorial, I explained the concept of negative indexing in Python arrays, such as what negative indexing is and why we use negative indexing. We have seen many real-time examples, and I have also shown some common issues and how to avoid them. Best practices for using negative indexing are also discussed in this article.

Hope this article helped you gain some knowledge of Array Index -1 in Python.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.