Store many values in one place. Create, read, change and sort lists, understand why two names can point at the same list, and use tuples for data that shouldn't change.
By the end of today you can
- Create lists and read items by index and slice
- Add, remove and sort items with list methods
- Explain the difference between sort() and sorted()
- Avoid the shared-list (aliasing) trap and copy lists safely
- Use tuples and unpacking
A list holds many values in order, in one variable: a shopping list, a list of scores, a list of users. A tuple is its read-only cousin.
Creating and reading lists
Lists use square brackets. Indexing and slicing work exactly like strings (Day 3):
Changing lists
Unlike strings, lists are mutable: you can change them in place.
| Method | What it does | Returns |
|---|---|---|
append(x) | Add x to the end | None |
insert(i, x) | Add x at index i | None |
extend(items) | Add every item from another list | None |
remove(x) | Remove the first x | None |
pop() / pop(i) | Remove and return the last (or i-th) item | the item |
sort() | Sort in place | None |
index(x) | Position of the first x | an int |
count(x) | How many times x appears | an int |
Sorting: sort() vs sorted()
Two names, one list
This surprises almost everyone once. A variable doesn't contain a list; it points to one. Assigning one variable to another makes a second name for the same list.
Lists of lists
A list can contain other lists. That's handy for tables and grids:
Tuples: sequences that don't change
A tuple uses parentheses and can't be changed after it's created. Use it for values that belong together and shouldn't change, like coordinates, RGB colours or a date.
| list | tuple | |
|---|---|---|
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Can change? | Yes (mutable) | No (immutable) |
| Typical use | A collection that grows or changes | A fixed record of related values |
Recap
- Lists are ordered and mutable; index and slice them like strings.
append,insert,removeandpopchange a list in place;sorted()returns a new list.b = ashares one list; usea.copy()for an independent copy.- Tuples are ordered and immutable; unpack them with
x, y = point.
Knowledge check
Test what you learned
5 questions · pick an answer to see if you're right
- 1
nums = [3, 1, 2]. What does nums.append(4) do?
- 2
What is the difference between nums.sort() and sorted(nums)?
- 3
a = [1, 2]; b = a; b.append(3). What is a?
- 4
Which statement about tuples is true?
- 5
What do x and y contain after x, y = (10, 20)?
Finished today's lesson?