2

I am trying to understand slicing. How does this slice work?

>>> a=['c','b']
>>> a
['c', 'b']
>>> a[-3:-1:3]
['c']

I have already read all the posts and cannot find an answer. As I understand it slice is supposed to be [start:stop:step]. But if I start at -3 after one step I am at 0. How exactly does this work? Which indexes are printed? The ones in the range?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
bubismark
  • 861
  • 1
  • 6
  • 8
  • 1
    Have you read the Python documentation on slicing? In the most basic case, it goes from `start` to `stop` in increments of `step`, excluding `stop`, but it gets a bit more complicated than that in some cases. – Pandu Dec 27 '13 at 22:22
  • 1
    Your problems appears to be with `start` and `stop`, not `step`. Negative start and stop indices count from the end (in a manner too complicated for me to reproduce faithfully in a comment). –  Dec 27 '13 at 22:25

2 Answers2

1

First note that a[-3:-1] is ['c']. a[-3:-1] is a slice containing all the elements in [a[-3], a[-2]], (if they exist).

>>> a=['c','b']
>>> a[-3:-1]
['c']

a[-3] does not exist (it raises an IndexError), but a[-2] is 'c':

>>> a[-2]
'c'

That makes sense, since a[-1] is the last element, 'b'. a[-2] is thus the penultimate element.

Finally,

>>> a[-3:-1:3]
['c']

since this is every third element in a[-3:-1]. Since there is only one element in a[-3:-1], every third element is the same as the first and only element.

The exact rules governing slicing is given by Notes 3 and 5 of the docs section entitled "Common Sequence Operations".

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
1

Think of the indexes as dividers right after an element. e.g.

Given list ['a', 'b', 'c']

Positive indexes (indexes in |n|): ['a'|0| 'b'|1| 'c'|2|]

Negative indexes (indexes in |n|), I'm gonna show the list in reverse so it's a bit more clear: ['c'|-1| 'b'|-2| 'a'|-3|] or in the original direction (but think of it starting from the end) [|-3|'a' |-2|'b' |-1|'c']

So in your example: a=['c','b'] your negative indexes are [|-2|'c' |-1|'b'] but when you're doing a range, Python doesn't complain when you pass an out of scope starting index of -3. In fact you can pass in any arbitrary indexes when you do a range and Python won't complain. Try for example [-10:-5], but because in your case your range does contain 'c', that's all you get.

misakm
  • 122
  • 6