-2

Consider the following code:

def mystr(L):
   print(L[0])
   return L[-1]

mystery_list = [2,5]
print(mystr(mystery_list))

Output (stdout):
2
5

I figure Python, once it goes into the negative zones, starts counting backwards? Therefore [-1] is the last element, [-2] is the second last element. Am I correct in this?

Does this behavior exist elsewhere in Python (ie: strings)?

If I create a copy of this list and I started at a negative number to 0 - will the list be inverted? ie newList = [-1:0] <-- will this invert the list?

Thanks.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
TimelordViktorious
  • 336
  • 3
  • 10
  • 20
  • You could simply try doing what you described and answer your question on your own... – That1Guy Nov 02 '15 at 21:54
  • Is your question the one about slicing/reversing a list or what? Yes, negative indices count from right. Yes, indexing is generally applicable to strings instead of lists -- anything with the methods that support it. And no, that will not reverse a list because the 'step' is still positive. Reverse is `[::-1]`. – Two-Bit Alchemist Nov 02 '15 at 21:54
  • Python does allow negative indexing into lists and sequence-like objects (tuples, strings, deques, etc.). – wkl Nov 02 '15 at 21:54
  • Support for negative indexes depends on the __getitem__ method of the class. AFAIK, all CPython built-in classes have this. Note that itertools.islice does not support negative indexes, but then, unbounded iterables may not even have a 'right end'. – Terry Jan Reedy Nov 03 '15 at 03:55

2 Answers2

1

Yes, indexing with a negative number is relative to the end of the list. This applies to python all python sequences (and a number of other objects that aim to behave like sequences).

If slicing is defined as sequence[i:j], then, according to the linked documentation

If i or j is negative, the index is relative to the end of the string: len(s) + i or len(s) + j is substituted. But note that -0 is still 0.

Some examples of sequences are:

  • string
  • unicode
  • tuple
  • list
  • xrange
  • bytearray
mgilson
  • 300,191
  • 65
  • 633
  • 696
0

Yes, you are correct in this assumption. Strings, tuples, lists, or any sequence all conform to this behavior and support negative indexing. Example:

Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
>>> a = [1, 2, 3, 4, 5]
>>> b = (1, 2, 3, 4, 5)
>>> c = "12345"
>>> print(a[-1])
5
>>> print(b[-1])
5
>>> print(c[-1])
5
Ethan Bierlein
  • 3,353
  • 4
  • 28
  • 42