vaanchit kaul
vaanchit kaul

Reputation: 17

Slicing lists in python

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

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

Upvotes: 0

Views: 1592

Answers (1)

Setop
Setop

Reputation: 2510

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.

Upvotes: 1

Related Questions