Negative indexing in python with example

What is a negative index in python?

- Python arrays & list items can be accessed with positive or negative numbers (also known as index).
- For instance our array/list is of size n, then for positive index 0 is the first index, 1 second, last index will be n-1. For negative index, -n is the first index, -(n-1) second, last negative index will be – 1.
- A negative index accesses elements from the end of the list counting backwards.
- An example to show negative index in python

>>> import array
>>> a= [1, 2, 3]
>>> print a[-3]
1
>>> print a[-2]
2
>>> print a[-1]
3

How do you make an array in Python?

How do you make an array in Python? - The array module contains methods for creating arrays of fixed types with homogeneous data types. Arrays are slower then list......

How to overload constructors (or methods) in Python

How to overload constructors (or methods) in Python - _init__ () is a first method defined in a class. when an instance of a class is created, python calls __init__() to initialize the attribute of the object.........

Python is a versatile language that you can use on the backend, frontend, or full stack of a web application. In this blog post, we will discuss negative indexing in Python. We will cover what it is and how to use it. Negative indexing can be confusing for beginners, but once you understand it, you will find that it is a very powerful tool. Let’s get started!

Understanding negative indexes in Python

Negative indexes are a way to allow you to index into a list, tuple or other indexable container relative to the end of the container, rather than the start.The reason this is called negative indexing is that the number you are using is less than the 0th element in the list.

They are used because they are more efficient and are considered by much more readable.

l = [0,1,2,3,4,5]
>>> l[-1]
5
>>> l[len(l) – 1]
5

Negative indexing in Python is when you use a negative number to index a list. For example, if we have a list of numbers:

>>> my_list = [0, 1, 2, 3]

And we want to get the last element in the list, we would use negative indexing:

>>> my_list[0] # Get the first element in the list
>>> my_list[-1] # Get the last element in the list

As you can see, we use the – sign to denote that we want to start counting from the end of the list.

012345
Python
-6-5-4-3-2-1

The first one will be significantly quicker.You can also use negative indexes in slices, and as with positive indexes, when you do a slice operation, the last element is not included in the slice

>>> l = [0,1,2,3,4,5]
>>> l[-3:-1]
[3,4]

As with positive indexes, the length of a slice can be calculated by subtracting the start index from the end index – in this case: −1−(−3)=−1+3=2 as demonstrated.you can even use negative indexes with negative steps to make a reversed slice :

> >>l = [0,1,2,3,4,5]
>>> l[-1:-4:-1]
[5,4,3]

here the 3rd value in the slice tells Python to go backwards from index -1 (the last element – number 5 here) to index -4 (i.e. 4th from the end – item 2 here), with the final element in the slice omitted.

use negative index in Python pop method

The pop() method takes a single argument (index) and removes the element at that index from the list. It also returns the removed element.If you don’t pass an index to the pop() method, it removes and returns the last element in the list.

>> my_list = [0, 1, 2, 3]
>>> my_list.pop() # Remove and return the last element in the list
3
>>> my_list.pop(0) # Remove and return the first element in the list
0
>>>my_list = [0, 1, 2, 3]
>>># print(my_list.pop(-1)) # Get the last element in the list

use negative index in Python insert method

The insert() method takes two arguments: the first is the index at which you want to insert the element, and the second is the value you want to insert.

>> my_list = [0, 1, 2, 3]
my_list.insert(1, 4) # Insert the element 4 at index 1
>>> my_list
[0, 4, 1, 2, 3]
>>> my_list.insert(0, -100) # Insert the element -100 at index 0
>>> my_list
[-100, 0, 11, 22, 33]
>>> my_list = [0, 11, 22, 33]
And we want to insert the element 44 at index -1
>>> my_list.insert(-1, 44)
>>> my_list
[0, 11, 22, 44, 33]

How to Get the Last Element of a Python List?

  • Negative Indexing for Strings
  • Negative Indexing for Lists
  • Related Code Puzzle

Negative Indexing for Strings

You can index single characters in strings using the bracket notation. The first character has index 0, the second index 1, and so on. Did you ever want to access the last element in the string? Counting the indices can be a real pain for long strings with more than 8-10 characters.

But no worries, Python has a language feature for this: negative indexing.

Positive Index: The first character has index 0, the second character has index 1, and the i-th character has index i-1.

Negative Index: The last character has index -1, the second last character has index -2, and the i-th last character has index -i.

Instead of start counting from the left, you can also start from the right. Access the last character with the negative index -1, the second last with the index -2, and so on.

x = 'cool'
print(x[-1] + x[-2] + x[-4] + x[-3])
# loco

Negative Indexing for Lists

Suppose, you have list ['u', 'n', 'i', 'v', 'e', 'r', 's', 'e']. The indices are simply the positions of the characters in the list.

(Positive) Index 0 1 2 3 4 5 6 7
Element ‘u’ ‘n’ ‘i’ ‘v’ ‘e’ ‘r’ ‘s’ ‘e’
Negative Index -8 -7 -6 -5 -4 -3 -2 -1

You can learn more about how to access the last and last n characters of a list or a string in our detailed article.

Related Article: How to Get the Last Element of a Python List?

In summary, there are two ways to index sequence positions, from the left and from the right with positive or negative indices.

Can you solve this code puzzle in our interactive puzzle app?

Negative indexing in python with example

Are you a master coder?
Test your skills now!

Negative indexing in python with example

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

What is negative indexing in Python with example?

Negative indexing in Python means the indexing starts from the end of the iterable. The last element is at index -1, the second last at -2, and so on.

Does Python allow negative indexing?

Python allows negative indexing for its sequences. The index of -1 refers to the last item, -2 to the second last item and so on.

What is negative indexing in string in Python?

Negative Indexing in Python Negative indexing accesses items relative to the end of the sequence. The index -1 reads the last element, -2 the second last, and so on. For example, let's read the last and the second last number from a list of numbers: nums = [1, 2, 3, 4] last = nums[-1]

What is the use of negative indexing?

Noun. (programming) The use of a negative integer as an array offset to access from the end of the array. Array[-3] accesses the 3rd element from the end of the array, the same as Array[ArraySize - 3] .