Skip to content

Module 8 · Python Data Structures — topic 5 of 22

Slicing

Take sub-lists with items[start:stop:step], copy and reverse lists, and use slice assignment to replace, insert or delete several items at once.

Beginner 12 min read·Lesson 108 of 306 in Python Programming

Learning objectives

  • Extract sub-lists with slices
  • Copy and reverse lists with slicing
  • Replace, insert and delete ranges with slice assignment

Definition

Take sub-lists with items[start:stop:step], copy and reverse lists, and use slice assignment to replace, insert or delete several items at once.

Introduction

Slicing works on lists exactly as on strings: items[1:4] returns a new list with the items at indexes 1, 2 and 3. Because lists are mutable, slices can also appear on the left of an assignment to change several items at once.

Why it matters

Slices extract the top three results, all but the header row, the most recent ten entries, or every second item, in a single expression. Slice assignment edits parts of a list without loops.

Detailed explanation

items[start:stop] includes start and excludes stop; omitted values mean the beginning or end.

items[-n:] gives the last n items; items[:-1] everything except the last.

items[::2] takes every second item; items[::-1] returns a reversed copy.

items[:] is a shallow copy: a new list containing the same item objects.

Slicing never raises IndexError; out-of-range positions are clipped.

Slice assignment replaces a range with the items of another iterable, and the lengths may differ: items[1:3] = ["a", "b", "c"] grows the list.

items[i:i] = [x] inserts at position i, and items[i:j] = [] or del items[i:j] removes a range.

Syntax

Python
part = items[start:stop]
last_three = items[-3:]
copy = items[:]
items[1:3] = ["a", "b"]
del items[::2]
  • Reading a slice returns a new list.
  • Assigning to a slice changes the list in place.
  • del removes the items in a slice.

Code examples

Reading slices

Python
nums = [10, 20, 30, 40, 50, 60]
print(nums[1:4])
print(nums[:2], nums[-2:])
print(nums[::2])
print(nums[::-1])
Output
[20, 30, 40]
[10, 20] [50, 60]
[10, 30, 50]
[60, 50, 40, 30, 20, 10]

Slice assignment

Python
letters = ["a", "b", "c", "d", "e"]
letters[1:3] = ["X", "Y", "Z"]
print(letters)
letters[0:0] = ["start"]
print(letters)
del letters[-2:]
print(letters)
Output
['a', 'X', 'Y', 'Z', 'd', 'e']
['start', 'a', 'X', 'Y', 'Z', 'd', 'e']
['start', 'a', 'X', 'Y', 'Z']

More examples

Working with ranked results

Python
scores = [72, 95, 88, 61, 99, 84, 77]
ranked = sorted(scores, reverse=True)
print("Top 3:", ranked[:3])
print("Rest:", ranked[3:])
print("Bottom 2:", ranked[-2:])
rows = ["name,mark", "Asha,82", "Ben,67", "Chen,91"]
header, data = rows[0], rows[1:]
print(header.split(","), len(data), "data rows")
recent = []
for entry in range(1, 13):
recent.append(entry)
recent = recent[-5:]
print("Last five entries:", recent)
Output
Top 3: [99, 95, 88]
Rest: [84, 77, 72, 61]
Bottom 2: [72, 61]
['name', 'mark'] 3 data rows
Last five entries: [8, 9, 10, 11, 12]

Step-by-step explanation

  • sorted(..., reverse=True) ranks the scores from highest to lowest.
  • [:3], [3:] and [-2:] split the ranking into the top three, the rest and the bottom two.
  • rows[1:] skips the header row of the data.
  • recent[-5:] keeps only the five newest entries after each append.

Expected output

Running “Working with ranked results” prints exactly:

TextOutput
Top 3: [99, 95, 88]
Rest: [84, 77, 72, 61]
Bottom 2: [72, 61]
['name', 'mark'] 3 data rows
Last five entries: [8, 9, 10, 11, 12]

Practical applications

  • Search pages show results[(page - 1) * 10 : page * 10] for each page.
  • Data scripts skip header rows with rows[1:].
  • Chat apps keep the most recent messages with messages[-50:].

Best practices

  • Use slices to split data into named parts.
  • Use [::-1] or reversed() for reversed views.
  • Use slice assignment sparingly; methods like insert() and remove() are often clearer.

Common mistakes

Assigning a single value to a slice

Avoid

items[1:3] = 0

Prefer

items[1:3] = [0]

Slice assignment needs an iterable; a plain int raises TypeError.

Assuming [:] makes a deep copy

Avoid

copy = grid[:]
copy[0][0] = 9 # changes grid too

Prefer

import copy
new_grid = copy.deepcopy(grid)

[:] copies the outer list only; inner lists are still shared (Module 17).

Key takeaways

  • items[start:stop:step] returns a new list.
  • [:] copies and [::-1] reverses.
  • Slice assignment and del can replace, insert or delete ranges in place.

Try it yourself

  1. 1
    Given a list of 12 monthly sales, print the first quarter and the last quarter using slices.
  2. 2
    Replace the middle three items of a 5-item list with a single item using slice assignment.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
Practise this topic