Skip to main content
← Python Study Guide

Code Scholars Tutoring · Python

3.1 Lists and Slicing

How it works

Lists are ordered and mutable. A slice takes start, stop, and step, and the stop index is excluded.

Mark both slice boundaries before evaluating, and use a negative step to reverse.

Common error

Treating the stop index as included, which yields a slice one item short of what you expected.

Worked example

Python

values = [2, 4, 6, 8]
copy = values[1:3]
copy.append(10)
print(values)
print(copy)

Output

[2, 4, 6, 8]
[4, 6, 10]

A list slice creates a new outer list. The stop index is excluded. With nested mutable objects, a shallow slice still shares those inner objects.

Exercises

3.1.1 · Trace

Determine the exact output and explain the state changes.

Python

values = [1, 2, 3, 4, 5]
print(values[::2])
print(values[::-1])
Show solution

Output

[1, 3, 5]
[5, 4, 3, 2, 1]

A step of 2 selects alternate positions; a negative step reverses traversal.

3.1.2 · Write code

Return a reversed copy of [3, 1, 4] while leaving the original unchanged.

Show solution

Slicing with a negative step makes a new outer list.

One valid solution

values = [3, 1, 4]
result = values[::-1]
print(values)
print(result)

Expected output

[3, 1, 4]
[4, 1, 3]
Open Python compiler

Need help with this topic?

Work through questions with a tutor and get help with the steps you find difficult.

Get help with this topic