Glossary

Slice

A slice is a syntax for extracting a sub-sequence from any sequence type (list, tuple, string, bytes, etc.). The syntax is sequence[start:stop:step], where start is the inclusive beginning index, stop is the exclusive ending index, and step is the stride. All three are optional: a[1:5] extracts elements 1 through 4, a[::2] takes every other element, and a[::-1] reverses the sequence.

Negative indices count from the end: a[-3:] returns the last three elements, and a[:-1] returns everything except the last element. Slicing never raises an IndexError, even if the indices are out of range — it simply returns what is available. This forgiving behaviour makes slicing safe and convenient.

Slices create new objects — slicing a list creates a new list (a shallow copy of the selected elements). This means b = a[:] is a common idiom for making a shallow copy. The slice() built-in creates slice objects that can be stored in variables and reused: s = slice(1, 5); a[s]. Custom classes can support slicing by implementing __getitem__ with a slice argument. NumPy extends slicing with advanced indexing features like boolean masking and multi-dimensional slicing.

Related terms: List, String, Tuple

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.