By abraham

2019-04-15 08:12:29 8 Comments

list = ["a", "b", "c", "d"]
print(list[3]) # Number 3 is "d"

print(list[-4]) # Number -4 is "a"


@Gregory Nisbet 2019-04-16 00:32:59

This idiom can be justified using modular arithmetic. We can think of indices as referring to a cell in a list obtained by walking forward i elements. -1 referring to the last element of the list is a natural generalization of this, since we arrive at the last element in the list if we walk backwards one step from the start of the list.

For any list xs and index i positive or negative, the expression


will either have the same value as the expression below or produce an IndexError:

xs[i % len(xs)]

The index of the last element is -1 + len(xs) which is congruent to -1 mod len(xs). For example, in an array of length 12, the canonical index of the last element is 11. 11 is congruent to -1 mod 12.

In Python, though, arrays are more often used as linear data structures than circular ones, so indexes larger than -1 + len(xs) or smaller than -len(xs) are out of bounds since there's seldom a need for them and the effects would be really counterintuitive if the size of the array ever changed.

@Ashish 2019-04-15 08:15:05

Because -0 in Python is 0.
With 0 you get first element of list and
with -1 you get the last element of the list

list = ["a", "b", "c", "d"]
print(list[0]) # "a"
print(list[-1]) # d

You can also think it as shorthand for list[len(list) - x] where x is the element position from the back. This is valid only if 0 < -(-x) < len(list)

print(list[-1]) # d
print(list[len(list) - 1]) # d
print(list[-5]) # list index out of range
print(list[len(list) - 5]) # a

@Koray Tugay 2019-04-15 15:43:47

I think -0 is 0 pretty much everywhere.

@Barmar 2019-04-15 16:24:17

@KorayTugay Except in floating point.

@Koray Tugay 2019-04-15 16:37:04

I guess that is not 0 anymore. @Barmar

@curiousdannii 2019-04-15 23:41:18

@KorayTugay It is. The binary representation is even all 0s. Floating point also just has another 0, where the sign bit is 1.

@Martin Bonner 2019-04-16 08:07:54

@Barmar There were architectures where 0 and -0 were distinct values even for integral values (sign and magnitude). I don't believe any processors now on the market use this representation though.

@JawSaw 2019-04-16 08:54:20

You could intuitively understand it this way

steps= ["a", "b", "c", "d"]

Suppose you start from a to d, a is your staring point where you stand (or your home), so mark it as 0(because you do not move),

Move one step to b, second step to c and arrive at third d.

Then how about you return from d to a (or return from your office to your home). Your home is 0 because your family live there, so your office cannot be a 0.It's your last stop.

So when you return back to home. d is the last first stop to start, c is the last second ....

@Raimund Krämer 2019-04-16 09:35:06

d is the last first stop to start, c is the last second This is kind of difficult to understand, could you dissect that sentence a bit?

@JawSaw 2019-04-16 10:02:31

last here is ending or final, not recent @RaimundKrämer

@T. Sar 2019-04-15 18:15:51

This is the mnemonic method I use. It is just an approach of what is happening, but it works.

Don't think of those as indexes. Think of them as offsets on a circular list.

Let's use the list x = [a,b,c,d,e,f,g,h] as an example. Think about x[2] and x[-2]:

enter image description here

You start at offset zero. If you move two steps forward, you're going from a to b (0 to 1), and them from b to c (1 to 2).

If you move two steps backward, you're going from a to h (0 to -1), and then from h to g (-1 to -2)

@detly 2019-04-15 22:54:48

"Think about a[2] and a[-2]" is a the list, or an element of the list?

@T. Sar 2019-04-16 02:27:04

"a" is an hypothetical list which contains the values a-h! I'll clarify!

@Code-Apprentice 2019-04-16 17:54:20

Note the similarity with modular arithmetic.

@recnac 2019-04-15 08:16:03

To explain it in another way, because -0 is equal to 0, if backward starts from 0, it is ambiguous to the interpreter.

If you are confused about -, and looking for another way to index backwards more understandably, you can try ~, it is a mirror of forward:

arr = ["a", "b", "c", "d"]
print(arr[~0])   # d
print(arr[~1])   # c

The typical usages for ~ are like "swap mirror node" or "find median in a sort list":

def reverse(arr):
    for i in range(len(arr)//2):
        arr[i], arr[~i] = arr[~i], arr[i]

def median(arr):
    mid = len(arr) // 2
    return (arr[mid] + arr[~mid]) / 2

~ actually is a math trick of inverse code and complement code, and it is more easy to understand in some situations.

Discussion about whether should use python tricks like ~:

In my opinion, if it is a code maintained by yourself, you can use any trick to avoid potential bug or achieve goal easier, because of maybe a high readability and usability. But in team work, avoid using 'too clever' code, may bring troubles to your co-workers.

For example, here is one concise code from Stefan Pochmann to solve this problem. I learned a lot from his code. But some are just for fun, too hackish to use.

def findStrobogrammatic(self, n):
    nums = n % 2 * list('018') or ['']
    while n > 1:
        n -= 2
        # n < 2 is so genius here
        nums = [a + num + b for a, b in '00 11 88 69 96'.split()[n < 2:] for num in nums]
    return nums

@Samuel Liew 2019-04-16 00:27:38

Comments are not for extended discussion; this conversation has been moved to chat.

@Konrad 2019-04-16 12:01:47

Could you provide description of the problem that Stefan's code solves? I don't want to register at leetcode only to access that information.It's also good when the answers contain all relevant details.

@recnac 2019-04-16 12:38:28

Problem Description: A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down). Find all strobogrammatic numbers that are of length = n. And the key points of Stefan's code: First line, if nums is odd, the middle will in '018', we will add pair to leftmost and rightmost in while loop, but we should consider number can not start with '0', so n<2 is used here. just 5 line solve a complex problem. @Konrad

@Paddy3118 2019-04-16 16:22:03

Donor use this method. You still need to understand the underlying use of negative indexing for indexing from the end. This is just further obfuscation.

@Oscar 2019-04-15 13:39:13

Another explanation:

Your finger points to the first element. The index decides how many places you shift your finger to the right. If the number is negative, you shift your finger to the left.

Of course, you cant step to the left from the first element, so the first step to the left wraps around to the last element.

@DroidX86 2019-04-15 08:14:48


Is short hand for:


The len(list) part is implicit. That's why the -1 is the last element. That goes for any negative index - the subtraction from len(list) is always implicit

@NicolasB 2019-04-15 12:17:16

In my opinion this answer is better than the accepted one.

@plugwash 2019-04-15 16:56:06

Be aware that list[-n] and list[len(list)-n] are only equivilent for values of n between 1 and len(list). This becomes especially important when slicing rather than indexing.

Related Questions

Sponsored Content

39 Answered Questions

[SOLVED] How to make a flat list out of list of lists

27 Answered Questions

[SOLVED] How do I list all files of a directory?

  • 2010-07-08 19:31:22
  • duhhunjonn
  • 3119772 View
  • 3413 Score
  • 27 Answer
  • Tags:   python directory

6 Answered Questions

[SOLVED] How do I get the number of elements in a list in Python?

  • 2009-11-11 00:30:54
  • y2k
  • 3046947 View
  • 1761 Score
  • 6 Answer
  • Tags:   python list

42 Answered Questions

[SOLVED] What does the "yield" keyword do?

27 Answered Questions

[SOLVED] Difference between append vs. extend list methods in Python

29 Answered Questions

[SOLVED] Finding the index of an item given a list containing it in Python

  • 2008-10-07 01:39:38
  • Eugene M
  • 3194984 View
  • 2636 Score
  • 29 Answer
  • Tags:   python list

20 Answered Questions

[SOLVED] How to clone or copy a list?

23 Answered Questions

[SOLVED] Accessing the index in 'for' loops?

  • 2009-02-06 22:47:54
  • Joan Venge
  • 1728671 View
  • 3024 Score
  • 23 Answer
  • Tags:   python loops list

19 Answered Questions

[SOLVED] How do I remove an element from a list by index in Python?

  • 2009-03-09 18:16:11
  • Joan Venge
  • 2160137 View
  • 1211 Score
  • 19 Answer
  • Tags:   python list

9 Answered Questions

[SOLVED] Python join: why is it string.join(list) instead of list.join(string)?

  • 2009-01-29 22:45:13
  • Evan Fosmark
  • 1179971 View
  • 1554 Score
  • 9 Answer
  • Tags:   python string list join

Sponsored Content