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

3

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Why is [1,2,3][::-1] and [1,2,3][0:3:-1] not same?
[::-1] means from end to start, step -1 which gives revered list. [0:3:-1] means from start to end step -1 which leads to empty.
This is an important answer. Other languages use [start:run length] and concentration can lapse.
@vaanchitkaul, [1,2,3][::-1] and [1,2,3][-1:-4:-1] are the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.