Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Operator []

Selects an item by index or a subsequence by slice.

Version: Python 3.14; repository image, production runtime not attested

Syntax

sequence[index]; sequence[start:stop:step]

Selects an item by index or a subsequence by slice.

An integer subscription selects one element. A slice passes a slice object with an excluded stop position; a negative step reverses the traversal direction.

Built-in sequences count negative indices from the end. A zero slice step raises a value error. Built-in list slices create a new outer list whose elements remain shared.

A slice extending beyond the end is clipped, while a single out-of-range index raises IndexError.

Syntax

sequence[index]; sequence[start:stop:step]

__getitem__ · slice(start, stop, step) · IndexError, ValueError

Worked example

[2, 5][-1] → 5
[2, 5][1:20] → [5]
[2, 5][20] → IndexError
[2, 5][::0] → ValueError
[3, 8, 4][::-1] → [4, 8, 3]

Examples

samples = [11, 17, 23]
print(samples[-1])
print(samples[1:20])

Result

23
[17, 23]

A slice extending beyond the end is clipped, while a single out-of-range index raises IndexError.

Sources