11
Lists
Lists: The Core Structure for Managing Groups of Data
What You Might Be Wondering
"I already have variables. Why do I need a list?"
Variables hold one value. Lists hold many. The moment you need to process a batch of anything, you'll reach for a list.
One-Line Definition
A list is an ordered, mutable container that supports adding, removing, modifying, searching, and iterating.
Real-Life Analogy
A list is like a shopping list: you can add items, cross them off, reorder, and check each one.
Minimal Working Example
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # apple
print(fruits[-1]) # cherry
CRUD Operations
nums = [3, 1, 4]
nums.append(2)
nums.insert(1, 99)
nums.remove(4)
last = nums.pop()
print(nums)
print(last)
Slicing & Sorting
scores = [80, 95, 70, 88]
print(scores[1:3])
print(sorted(scores))
scores.sort(reverse=True)
print(scores)
Iteration with Index
for i, val in enumerate(scores):
print(i, val)
Quick Quiz (5 min)
- Create a shopping list, then add and remove items.
- Given a list of prices, find the max, min, and average.
- Print each element along with its index.
Quiz Rubric & Grading Criteria
- Direction: write runnable code that covers the core requirements and edge cases from the prompt.
- Criterion 1 (Correctness): main flow produces correct results, key branches execute.
- Criterion 2 (Readability): clear variable names, no excessive nesting.
- Criterion 3 (Robustness): basic protection against empty values, type errors, or unexpected input.
Take-Home Task
Build a "score dashboard":
- Input: a list of scores
- Output: average, highest, and lowest
- Output: scores in descending order
Acceptance Criteria
You can independently:
- Add, remove, update, and read list elements
- Use slicing and sorting correctly
- Process batch data with loops
Common Errors & Debugging Steps (Beginner Edition)
- Error message looks like gibberish: read the last line for the error type (
TypeError,NameError, etc.), then trace back to the offending line. - Not sure what a variable holds: drop a temporary
print(variable, type(variable))to check. - Changed code but nothing happened: make sure you saved the file, you're running the right file, and your terminal environment (venv) is correct.
Common Misconceptions
-
Misconception:
removeandpopdo the same thing. -
Reality:
removedeletes by value.popdeletes by index and returns the removed element. -
Misconception: it's fine to modify a list's length while iterating over it.
-
Reality: that's a recipe for skipped elements. Copy the list first if you need to modify it.