Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Indexing and slicing

Indexing and slicing are very general, can be used on all sequences as str, list, etc... Not simple for beginners but very powerful (see here and here).

We consider a string of six elements.

s = "abcdef"

Indexing

One can index with positive integers:

s[0], s[2]
('a', 'c')

Negative integers are used to index from the end. -1 corresponds to the last element.

s[-1], s[-2]
('f', 'e')

Slicing

Slicing is a syntax to get a piece of a sequence. The syntax uses brackets and a “slice” with one or two colon(s): s[start:stop] or s[start:stop:step], where start, stop and step can be written or omitted.

s[0:4:1]
'abcd'
s[0:4]
'abcd'
s[0:4:2]
'ac'
s[:]
'abcdef'
s[::]
'abcdef'
s[2::]
'cdef'
s[:2:]
'ab'
s[::2]
'ace'
s[::-1]
'fedcba'

The rules are that start corresponds to the first element and that one stops before the stop.

Image stop passage à niveau

Summary

Python indexes and slices for a six-element str. Indexes enumerate the elements, slices enumerate the spaces between the elements.

Index from rear:    -6  -5  -4  -3  -2  -1
Index from front:    0   1   2   3   4   5
                   +---+---+---+---+---+---+
                   | a | b | c | d | e | f |
                   +---+---+---+---+---+---+
Slice from front:  0   1   2   3   4   5   6
Slice from rear:  -6  -5  -4  -3  -2  -1   0
# s[start:stop:step]
s[2:6:2]
'ce'

Other examples of slices for a six-element list. Indexes enumerate the elements, slices enumerate the spaces between the elements.

a = [0, 1, 2, 3, 4, 5]
all(
    [
        len(a) == 6,
        a[1:] == [1, 2, 3, 4, 5],
        a[:5] == [0, 1, 2, 3, 4],
        a[0] == 0,
        a[:-2] == [0, 1, 2, 3],
        a[5] == 5,
        a[1:2] == [1],
        a[-1] == 5,
        a[1:-1] == [1, 2, 3, 4],
        a[-2] == 4,
    ]
)
True

Built-in function slice

In python, the built in slice is another way to access elements of sequence:

sl_2_elems = slice(0, 2)  # get the first two elements
print(a[sl_2_elems])
last_elems = slice(2, None)  # get the last elements
print(a[last_elems])
[0, 1]
[2, 3, 4, 5]

If the same slice is used at different part of the code, then storing a slice object and reusing it elsewhere might be more practical than rewriting the slice each time.