Skip to content

Computer Science · Ch 9 — Lists

Slicing

9.2.4

Slicing

The slicing operation that extracts substrings from a string applies to lists as well: list[start:stop] returns a new list containing the elements from index start up to but not including index stop. An optional third value, list[start:stop:step], picks every step-th element. All the examples below use one working list:

>>> shades = ['White', 'Grey', 'Silver', 'Gold', 'Bronze', 'Copper', 'Brown']

A basic slice

>>> shades[2:6]     # indices 2, 3, 4, 5 — index 6 excluded
['Silver', 'Gold', 'Bronze', 'Copper']

When the second index is out of range

If stop runs past the end of the list, the slice is simply truncated at the end of the list — no error is raised:

>>> shades[2:20]    # second index out of range
['Silver', 'Gold', 'Bronze', 'Copper', 'Brown']

When the first index is greater than the second

A slice whose start lies at or beyond stop selects nothing and yields an empty list:

>>> shades[6:2]     # first index > second index
[]

Leaving an index out

A missing start defaults to the beginning of the list; a missing stop defaults to its end:

>>> shades[:5]      # first index missing — from index 0 to 4
['White', 'Grey', 'Silver', 'Gold', 'Bronze']

Slicing with a step size

The third value skips through the selected range:

>>> shades[0:6:2]   # every second element among indices 0..5
['White', 'Silver', 'Bronze']

Negative indexes in slices

Negative positions count from the right, exactly as in single-element indexing. Here the elements at indexes -6, -5, -4 and -3 are sliced:

>>> shades[-6:-2]
['Grey', 'Silver', 'Gold', 'Bronze']

Both indices missing, with a step

Omitting both start and stop takes the whole list, and the step then thins it out:

>>> shades[::2]     # step size 2 over the entire list
['White', 'Silver', 'Bronze', 'Brown']

A negative step — the list in reverse

A step of -1 walks the list backwards, so [::-1] produces the whole list in reverse order:

>>> shades[::-1]
['Brown', 'Copper', 'Bronze', 'Gold', 'Silver', 'Grey', 'White']

Key points

  • list[start:stop] includes start, excludes stop. …