0

There is a hell lot of confusion on how exactly does slice operation work on lists.

  • Why does [1,2,3,4][::-1] return its reverse?

  • Why does [1,2,3,4][1:-4] return [] and [1,2,3,4][1:-4:-1] return [2] ?

The main problem occurs when using negative indices.

It will be good if someone could show me the exact definition of slice in the built-in module.

Edit: Why do [1,2,3][::-1] and [1,2,3][0:3:-1] have different return values

vaanchit kaul
  • 17
  • 1
  • 8

1 Answers1

1

List ['A', 'B', 'C', 'D']

Index from 0 to size-1.

Negative index means going through the list backward :

       negative index   |   positive index
-5   -4   -3   -2   -1  |  0    1    2    3    4
     'A'  'B', 'C', 'D',|['A', 'B', 'C', 'D']

Index > 4 or < -5 throw IndexError.

Slices follow this pattern : List[from:to:step]

  • step, defaults to one, indicates which indexes to keep in slice its sign gives the direction of slicing
    • positive, for left to right,
    • negative for right to left
  • from index where to start the slicing, inclusive
    • defaults to 0 when step is positive,
    • defaults to -1 when step is negative
  • to index where to end the slicing, exclusive
    • default to size-1 when step is positive,
    • (size-1) when step is negative

examples :

['A','B','C','D'][::-1] means from right to left, from -1 to -(size-1) => ['D', 'C', 'B', 'A']

['A','B','C','D'][1:-4] means from second element to first element excluded with step of one => nothing

['A','B','C','D'][1:-4:-1] means from second element to first element excluded with step of minus one, only second element left => [2]

Of course, the best is always to try a slice on samples before using it.

Setop
  • 2,262
  • 13
  • 28