Week 5 of 106 hours5 exercises
Week 5: Lists and tuples
Keep many values together, change them, sort them and filter them with list comprehensions.
By the end of this week you can
- Create lists and use indexes and slices
- Add, remove and sort items
- Loop over lists and build new ones
- Know when a tuple is the right choice
Lists: ordered collections
A list holds many values in order, written in square brackets. Indexing and slicing work exactly as they did for strings: the first item is at 0 and -1 is the last. Unlike strings, lists can be changed in place.
Items can be of any type, even mixed, though most lists hold one kind of thing such as marks or names. len() gives the number of items.
sum, max and min work on any list of numbers.
Changing a list
append(x) adds to the end, insert(i, x) adds at a position, remove(x) deletes the first matching value and pop() removes and returns an item (the last one unless you give an index).
sort() puts the list itself in order and returns nothing. sorted(list) returns a new sorted list and leaves the original alone. Add reverse=True for largest first. The word in checks membership.
A common slip is writing nums = nums.sort(), which stores None. sort() changes the list and returns nothing.
Looping and list comprehensions
A for loop visits each item directly, with no index needed. When you want the position as well, use enumerate().
A list comprehension builds a new list in one line from a loop and an optional condition: [expression for item in items if condition]. Start with a normal loop until the shape is familiar, then compress it.
The comprehension is the same as: passed = [] then a for loop that appends each m that is at least 50.
Tuples: lists that do not change
A tuple looks like a list but uses round brackets, and cannot be changed after it is created. Use one for a small group that belongs together, such as a point (x, y) or a (name, marks) pair. Python often creates tuples for you, and you can unpack them into separate names in one go.
Swapping two variables in one line works because the right side becomes a tuple first.
Common mistakes
- Writing marks = marks.sort(). The method returns None, so marks becomes None.
- Using an index that does not exist. A list of 4 items has indexes 0 to 3, so marks[4] is an IndexError.
- Copying with b = a. Both names then point to the same list. Use b = a.copy() or b = a[:] for a separate copy.
- Removing items from a list while looping over it, which skips items.
Quick recap
- Lists are ordered and changeable; tuples are ordered and fixed.
- append, insert, remove and pop change a list; sort() changes in place, sorted() returns a new list.
- Comprehensions build a new list from a loop in one line.
- b = a shares one list; use .copy() for a separate one.
Practise this week
Work through the 5 exercises for Week 5. Each one tells you which tests pass, and has a hint and a solution if you get stuck.
Check your understanding
Pick an answer for each question, then press Check answers.
This course is for learning. The Python engine runs in your browser and your code is never sent to us.