Lists
Ordered and changeable
Ordered, unchangeable collections
Unit 3 · Data Structures
A data structure organizes values so a program can find and work with them. Explore four built-in Python structures and use each lab to see how its rules affect real data.
Ordered and changeable
Ordered and fixed
Unique values
Key → value lookup
Ordered · not changeable · duplicates allowed
A tuple stores a sequence like a list, but its items cannot be reassigned, added, or removed after creation. Use parentheses for clarity; a one-item tuple needs a trailing comma, such as (5,).
Think of a printed result slip: its recorded marks stay fixed. You can read a position or copy its values into new names, but the original tuple remains unchanged.
Select a position to retrieve its value. The tuple has four marks and cannot be edited in this lab.
marks[0] returns 91.
marks[0]Read by position.
marks[:2]Slice the first two values.
a, b = (1, 2)Unpack values into names.
marks = [91,82,76,88]
print("Selected item:", marks[0])
print("First two:", marks[:2])
first, second, *remaining = marks
print("Unpacked:", first, second, remaining)Output
Your program's output will appear here.
NameError: name 'mark' is not defined
NameError: A name was used before Python could find a variable or function with that name.
IndexError: list index out of range
IndexError: The requested position is outside the items in this list or sequence.
KeyError: 'email'
KeyError: That key does not exist in this dictionary.
TypeError: can only concatenate str (not "int") to str
TypeError: This operation does not work with the kind of value it received.
ZeroDivisionError: division by zero
ZeroDivisionError: A number cannot be divided by zero.
SyntaxError: invalid syntax
SyntaxError: Python could not understand the structure of this line. Check spelling, brackets, colons, and quotes.
IndentationError: expected an indented block
IndentationError: The spaces at the start of a line do not match Python's block structure.
("OS",), including the comma.marks[0] = 100 raises a TypeError. Create a new tuple if the values must change.1. How do you write a tuple containing only the number 5?
2. Can you replace an item in an existing tuple?
Ask two questions: does order matter, and should the collection change after creation?
| Structure | Ordered? | Changeable? | Access values by |
|---|---|---|---|
| list | Yes | Yes | Position (index) |
| tuple | Yes | No | Position (index) |
| set | No guaranteed order | Yes | Membership, not index |
| dict | Insertion order is preserved | Yes | Key |
Use a list for a sequence that changes, a tuple for a fixed record, a set for unique membership, and a dictionary for named lookups.