Python course · Part 4: Collections · lab 4 of 7
Lists, dictionaries and sets
Slicing and sorting, dictionaries that count and group, sets for uniqueness, and the copying trap that makes one change show up in two places.
By the end you can
- Slice and sort a list, including sorting by something other than the value
- Count and group records with a dictionary
- Remove duplicates without losing the order
- Copy a list or dictionary properly, instead of sharing one by accident
Easier if you did first
step 1 of 4
Slices and sorting
A list is ordered, and positions count from zero. items[0] is the first. items[-1] is the last, counting backwards, which saves working out the length.
A slice takes a run of them: items[1:4] is positions 1, 2 and 3. The first number is where to start, the second is where to stop, and the stop is not included. That sounds arbitrary until you notice it means items[:2] and items[2:] split the list perfectly with nothing lost or repeated.
sorted(items) gives you a new sorted list and leaves the original alone. items.sort() changes the list in place and returns None, which is a classic source of "why is my list suddenly None".
The useful part is key. sorted(jobs, key=lambda job: job["total"]) sorts by whatever you say rather than the whole value, and reverse=True turns it round.
Write the three.
items = ["a", "b", "c", "d"]
items[0] # "a"
items[-1] # "d"
items[1:3] # ["b", "c"]
items[:2] # ["a", "b"]
items[2:] # ["c", "d"]
sorted(jobs, key=lambda job: job["total"], reverse=True)What these words mean
- items[-1]
- The last item.
- items[a:b]
- From a up to but not including b.
- sorted(x)
- A new sorted list. The original is untouched.
- x.sort()
- Sorts in place and returns None.
- key=
- What to sort by.
- lambda
- A small function written inline.
Easy to get wrong
jobs = jobs.sort()
jobs.sort() or jobs = sorted(jobs)
.sort() returns None, so assigning its result throws your list away and replaces it with nothing. The error then appears somewhere else entirely.
items[len(items) - 1]
items[-1]
It works, but it is longer and breaks on an empty list in a more confusing way. Negative indexes exist for exactly this.
What we check
- The three biggest come back, biggest first
- Fewer than three is not an error
- No jobs gives no names
- The list you were given is not reordered behind your back
- The middle is everything but the ends
- Short lists give an empty list rather than failing
- Rotating by one moves the first to the end
- Rotating by nothing changes nothing
- Rotating by the whole length comes back round
- It printed the top jobs
Nothing printed yet. Run your code.