Why do we use negative indexing in python?

110

New! Save questions or answers and organize your favorite content.
Learn more.

I'm trying to understand the following piece of code:

# node list
n = []
for i in xrange(1, numnodes + 1):
    tmp = session.newobject();
    n.append(tmp)
link(n[0], n[-1])

Specifically, I don't understand what the index -1 refers to. If the index 0 refers to the first element, then what does -1 refer to?

Why do we use negative indexing in python?

Henry Ecker

32.7k17 gold badges30 silver badges51 bronze badges

asked Jul 6, 2012 at 18:41

2

Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.

answered Jul 6, 2012 at 18:43

ToomaiToomai

3,8461 gold badge20 silver badges22 bronze badges

4

List indexes of -x mean the xth item from the end of the list, so n[-1] means the last item in the list n. Any good Python tutorial should have told you this.

It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1] to access the last item of a list.

answered Jul 6, 2012 at 18:43

Russell BorogoveRussell Borogove

17.9k3 gold badges39 silver badges48 bronze badges

2

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2022 by Refsnes Data. All Rights Reserved.
W3Schools is Powered by W3.CSS.


Negative Indexing is used to in Python to begin slicing from the end of the string i.e. the last. Slicing in Python gets a sub-string from a string. The slicing range is set as parameters i.e. start, stop and step.

Syntax

Let us see the syntax −

#slicing from index start to index stop-1
arr[start:stop]

# slicing from index start to the end
arr[start:]

# slicing from the beginning to index stop - 1
arr[:stop]

# slicing from the index start to index stop, by skipping step
arr[start:stop:step]

If the values above are in negative, that would mean negative indexing i.e. slicing from the end of the string.

Slice a String with Negative Indexing

Example

myStr = 'Thisisit!' print("String = ", myStr) print("String after slicing (negative indexing) = ", myStr[-4:-1])

Output

String =  Thisisit!
String after slicing (negative indexing) =  sit

Slice a String with Negative Indexing and set a step

The slicing range is set as parameters i.e. start, stop and step. For negative indexing, set the start and stop as negative values i.e slice from the end −

Example

myStr = 'Thisisit. We did it!' print("String = ", myStr) print("String after slicing (negative indexing) = ", myStr[-9:-3:2])

Output

String =  Thisisit. We did it!
String after slicing (negative indexing) =  edd

Reverse the order of a string with Negative Indexing

To display the 1st element to last element in steps of 1 in reverse order, we use the [::-1]. The [::-1] reverses the order

Example

Let’s see the example

myStr = 'Hello! How are you?' print("String = ", myStr) print("Reverse order of the String = ", myStr[::-1])

Output

String =  Hello! How are you?
Reverse order of the String =  ?uoy era woH !olleH

Why do we use negative indexing in python?

Updated on 16-Sep-2022 12:17:41

  • Related Questions & Answers
  • Python Indexing a sublist
  • Boolean Indexing in Python
  • What is negative infinity in javascript?
  • Python Pandas - Create a Subset DataFrame using Indexing Operator
  • Basic Slicing and Advanced Indexing in NumPy Python
  • What are the techniques of Text Indexing?
  • Boolean Indexing in Pandas
  • Add the element in a Python list with help of indexing
  • What is Negative Testing(Test cases with Example)?
  • Is their a negative lookbehind equivalent in JavaScript?
  • What kind of indexing can be done on a PostgreSQL table?
  • What happens when a negative value is inserted to UNSIGNED column in MySQL?
  • Python Program to Check if a Number is Positive, Negative or 0
  • Python program to print negative numbers in a list
  • How to check if a number is positive, negative or zero using Python?
  • Indexing numbers to alphabets in JavaScript

Why do we need negative indexing?

The use of negative indexing can be done to use or display data from the end of the list and can also be used to reverse a number or string without using other functions.

What is the use of negative indices in slicing?

Negative Slicing in Python The slicing ends at the last item, which is at the index -1. Also, the step size can be a negative value. By doing this, the direction of slicing is reversed. This means the slicing starts from the sequence[stop + 1] and stops at the sequence[start] value.

What does a negative index mean?

What are negative indices? Negative indices are powers (also called exponents) with a minus sign in front of them. E.g. x−2. 3−4.

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.