Slicing Lists & Strings

Published by Brayan K

Slicing is the syntax seq[start:stop:step] for extracting a new sub-sequence — a range of elements from a list, string, or tuple — without writing a loop.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

Put the stop just beyond the part you want

A slice selects positions, not the values stored at those positions. Start counting at zero: in this timetable, Monday is at index zero and Thursday is at index three. To take Monday through Wednesday, stop at index three. Python includes the start and leaves out the stop.

days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
# Stop just before the day at index 3.
morning_group = days[:3]
remaining = days[3:]
print(morning_group)
print(remaining)
print(morning_group + remaining == days)

# ✅ Expected output:
# ['Mon', 'Tue', 'Wed']
# ['Thu', 'Fri']
# True

Leaving the start blank means the beginning for a forward slice. Leaving the stop blank means the end. The two slices meet at the same boundary, so the day at that boundary belongs only to the second piece. This is useful when splitting a queue into the part you will handle now and the part you will keep.

An index retrieves one item; a slice retrieves a sequence. Adding, removing and looking up individual list items belong to Lists in Python. Here the focus is selecting or replacing a range.

Bounds can reach beyond the sequence

For built-in lists, strings and tuples, an out-of-range slice bound is clipped to the available range. It does not demand that an item exists at the stop. A start beyond the end gives an empty sequence when moving forwards. This makes a request for the first ten items work even when only three exist.

word = "cobalt"
print(word[:100])
print(repr(word[100:]))
print(word[-3:])
print(repr(word[4:2]))

# ✅ Expected output:
# cobalt
# ''
# alt
# ''

A negative bound counts from the end: minus one refers to the final item, minus two to the item before it. A negative start does not reverse the direction. With the default positive step, a start to the right of the stop selects nothing. The repr() calls make an empty string visible instead of leaving a puzzling blank output line.

A step chooses positions and a direction

The third field is the step. A step of two takes every other position from the chosen start. A negative step moves towards lower indexes. Its omitted bounds are chosen for that direction, which is why leaving a bound empty is not always the same as writing minus one.

letters = "abcdef"
print(letters[::2])
print(letters[::-1])
print(letters[5:0:-1])
print(letters[5::-1])
print(repr(letters[5:-1:-1]))

# ✅ Expected output:
# ace
# fedcba
# fedcb
# fedcba
# ''

The slice ending at index zero still excludes that index, even while moving backwards. Leaving the stop empty allows the backwards walk to include the first item. An explicit stop of minus one instead refers to the last item; starting there and stopping before it leaves no positions to visit.

A zero step cannot advance through a sequence. It raises an error rather than meaning “keep every item”:

letters = "abcdef"
print(letters[::0])

# ✅ Expected error:
# ValueError: slice step cannot be zero

Use one to keep consecutive positions, or a larger positive step to skip positions. The corrected program takes every second letter:

letters = "abcdef"
print(letters[::2])

# ✅ Expected output:
# ace

A list slice copies the outer list

Reading a slice of a built-in list creates another list. Replacing an item in that new list leaves the original list alone. The copy is shallow: if the items are themselves lists, both outer lists still refer to those same inner lists. Slicing does not recursively copy their contents.

rows = [["Ada"], ["Lin"]]
copied = rows[:]
print(copied is rows)
copied[0].append("reviewed")
copied[1] = ["Jo"]
print(rows)
print(copied)

# ✅ Expected output:
# False
# [['Ada', 'reviewed'], ['Lin']]
# [['Ada', 'reviewed'], ['Jo']]

Appending inside the first row changes a shared inner list. Replacing the second row changes only which object the copied outer list refers to. Do not turn this into a promise about object identity for every sequence type: immutable strings and tuples may reuse objects. Their contents, rather than whether a new object was allocated, are what a slice promises.

Assigning to a slice changes the original list

A slice on the left of an equals sign has a different job: it replaces a region of a mutable sequence. For a list slice with the default step of one, the replacement can have a different length. Assigning an empty list removes that region; assigning to an empty region inserts there.

tasks = ["read", "draft", "edit", "send"]
tasks[1:3] = ["review"]
print(tasks)
tasks[1:1] = ["plan"]
print(tasks)
tasks[1:3] = []
print(tasks)

# ✅ Expected output:
# ['read', 'review', 'send']
# ['read', 'plan', 'review', 'send']
# ['read', 'send']

With a step other than one, the selected positions are separate slots. The replacement must supply exactly one item for each slot. This assignment selects three slots but provides only one item:

letters = list("abcdef")
letters[::2] = ["X"]

# ✅ Expected error:
# ValueError: attempt to assign sequence of size 1 to extended slice of size 3

Supply three replacements so the unselected positions keep their places. Strings cannot be edited by slice assignment; build a new string from pieces when text needs changing.

letters = list("abcdef")
letters[::2] = ["A", "C", "E"]
print(letters)
word = "colour"
revised = word[:4] + word[5:]
print(revised)
print(word)

# ✅ Expected output:
# ['A', 'b', 'C', 'd', 'E', 'f']
# color
# colour

Select alternating seats

The seating list has seven entries. Fill the three blanks to select the entries at indexes one, three and five, while leaving the original list unchanged. Decide the start, the first excluded position and the step separately.

seats = ["A", "B", "C", "D", "E", "F", "G"]
selected = seats[___:___:___]
print(selected)
print(seats)

# 👉 replace ___ with 1
# 👉 replace ___ with 6
# 👉 replace ___ with 2

# ✅ Expected output:
# ['B', 'D', 'F']
# ['A', 'B', 'C', 'D', 'E', 'F', 'G']

Prepare a compact activity report

A log contains a header, five activity names and a footer. Starting with the list in the solution, create a report containing only the activities, take the newest two activities and display those two in reverse order. Keep the log intact and print it afterwards to demonstrate that reading slices did not edit it. Write your three slice expressions before opening the solution.

log = ["HEADER", "open", "read", "edit", "save", "close", "FOOTER"]
activities = log[1:-1]
recent = activities[-2:]
print(activities)
print(recent[::-1])
print(log)

# ✅ Expected output:
# ['open', 'read', 'edit', 'save', 'close']
# ['close', 'save']
# ['HEADER', 'open', 'read', 'edit', 'save', 'close', 'FOOTER']

Practice quiz

What does this program print? print("abcdef"[1:4])

  • abcd
  • bcd
  • bcde
  • An IndexError

Answer: bcd. Index one is included and index four is excluded.

What does this program print? print(repr("abc"[9:]))

  • An IndexError
  • None
  • abc
  • ''

Answer: ''. A forward start beyond the end selects an empty string; repr makes its quotes visible.

What does this program print? print("abcdef"[-3:])

  • def
  • abc
  • cde
  • fed

Answer: def. Minus three locates the third character from the end; the omitted stop reaches the end.

What does this program print? print("abcdef"[5:0:-1])

  • fedcba
  • abcdef
  • fedcb
  • An IndexError

Answer: fedcb. A negative step moves backwards, but the explicit stop at index zero is still excluded.

What does this program print? print(repr("abc"[2:-1:-1]))

  • cba
  • ''
  • cb
  • An IndexError

Answer: ''. Explicit minus one refers to the last position, which is also the start here.

What does this program print? values = [1, 2, 3] part = values[:2] part[0] = 9 print(values)

  • [9, 2, 3]
  • [9, 2]
  • [1, 2]
  • [1, 2, 3]

Answer: [1, 2, 3]. A built-in list slice creates a separate outer list.

What does this program print? values = [1, 2, 3, 4] values[1:3] = [8] print(values)

  • [1, 8, 4]
  • [1, 8, 3, 4]
  • [1, 8, 8, 4]
  • A ValueError

Answer: [1, 8, 4]. A contiguous list slice can be replaced by a shorter sequence.

Why does letters[::2] = ["X"] fail for a six-item list?

  • A list can never change length
  • Strings cannot be stored in a list
  • The slice selects three positions but the replacement supplies one item
  • A step of two is invalid

Answer: The slice selects three positions but the replacement supplies one item. Extended-slice replacement must match the number of selected positions.

Continue this course

Related lessons