2

I do not know much about python, but I am surprised the following code works:

import sys
prev =  [sys.maxint]*(5)
j = 0
print prev[j]
print prev[j-1]

In general I thought second print statement should give me an error. Why does this work?

I need to convert some python code into C++, and in C++ this will not work.

NullUserException
  • 83,810
  • 28
  • 209
  • 234
Avinash
  • 12,851
  • 32
  • 116
  • 186
  • Next question: [Good Primer for Python Slice Notation](http://stackoverflow.com/questions/509211/good-primer-for-python-slice-notation) – Greg Hewgill Dec 01 '11 at 18:32

4 Answers4

5

mylist[-1] returns the last item of mylist, mylist[-2] the second-to-last item etc.

This is by design. Read the tutorial.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
2

That's because j - 1 evaluates to -1, which when used as index of python list, means last element.

soulcheck
  • 36,297
  • 6
  • 91
  • 90
2

The index of an array l can be an integer in the range [-len(l), len(l)-1] (note: inclusive on both ends). You are familiar with the indices in the range [0, len(l)-1]. The indices in the range [-len(l),-1] are as follows: take i in that range, then l[i] == l[len(l) + i]. Essentially, negative numbers count backwards from the end of the array.

Thus, prev[j-1] = prev[-1] = prev[len(prev) + -1] = prev[5 - 1] = prev[4], or the last element in the array.

Aaron Dufour
  • 17,288
  • 1
  • 47
  • 69
1

In python x[-1] returns the last element in a list

TJD
  • 11,800
  • 1
  • 26
  • 34