Phase 2: Programming Fundamentals II · ~35 minutes · Python · uv
Lists and Tuples — Ordered Collections
list[1:3] stops before index 3, not at it. Every slicing bug you'll ever write traces back to forgetting that one fact.
Real-world application: Chooses list vs. tuple deliberately, and reasons correctly about slice boundaries instead of guessing and checking
What you will learn
- Create, index, slice, and mutate lists; explain why tuples can't be mutated the same way
- Explain why slicing is exclusive on the end index and use that rule to avoid off-by-one bugs
- Diagnose a real IndexError by tracing it back to a boundary miscalculation
- Decide when immutability (a tuple) is the right choice over a list
Introduction
- Type: Learn
- Languages: Python
- Prerequisites: Programming Fundamentals I
- Time: ~35 minutes
Objective
Learning objectives
- Create, index, slice, and mutate lists; explain why tuples can't be mutated the same way
- Explain why slicing is exclusive on the end index and use that rule to avoid off-by-one bugs
- Diagnose a real
IndexError by tracing it back to a boundary miscalculation - Decide when immutability (a tuple) is the right choice over a list
What you're building
A script (student_records.py) using this data:
students = [
{"name": "Ada", "grade": 92},
{"name": "Grace", "grade": 88},
{"name": "Alan", "grade": 95},
{"name": "Katherine", "grade": 90},
{"name": "Edsger", "grade": 78},
]
That:
- Filters this list to only students with a grade of 90 or above
- Slices out the last two students in the original list (using a negative, open-ended slice, not hardcoded positions)
- Reorders the original list so it's sorted by grade, highest first (
sorted(..., key=..., reverse=True)) - Contains a comment demonstrating the
students[len(students)] off-by-one mistake and its fix
Given numbers = [10, 20, 30, 40, 50], what does numbers[-3:-1] return?
Negative indices count from the end: -3 is 30, -2 is 40, -1 is 50. The slice numbers[-3:-1] starts at -3 (30) and stops before -1 (50) — so it includes -3 and -2, giving [30, 40]. The "stop is never included" rule from this lesson applies identically whether the indices are positive or negative, and mixing two negative indices in one slice is completely valid Python.
This lesson is free
You've read the first 2 sections. The rest covers The Problem, Check Yourself, Key Terms & Next. A free account opens all of it, with its practice questions and its lab. No card.
Create a free account — the opening phases of 29 of 35 courses, and the first lesson of every phase, are free, no credit card.
Browse all courses · View pricing · DeVenture Academy