Lesson 5 of 10
Changing lists
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
Add, remove and copy
Explanation
A list holds several values in order, like queue = ["Sara", "Omar"], and you read from it exactly the way you read from a string: queue[0] is the first item, queue[-1] is the last, and queue[:2] gives you the first two in a new list. len(queue) gives you the number of items, and "Omar" in queue asks whether Omar is in it.
The difference from strings is that lists can change: append(x) adds an item at the end, insert(0, x) adds it at the position you choose, remove(x) deletes the first occurrence of a value, and pop(0) removes the item at the given position and returns it to you. All of these change the list itself instead of creating a new one.
That's where the most famous list mistake comes from: b = a doesn't copy anything, it just gives the same list a second name, so when you change b, a changes with it. If you want an independent copy, write a.copy().
Your task
Make queue a copy of original and change only the copy: add Khalid to the end of the line, put Noor at the front because she has priority, and remove Omar because he left. Then the first person in line gets served, so remove them from the queue and store them in served. Finally, put the first two people still waiting into next_two.
Checks
6 checks- original is unchanged because queue is a copy, not a second name
- Khalid is at the end of the line
- Omar has left the line
- served is "Noor" because she was served first
- The line is now Sara, then Layan, then Khalid
- next_two holds the first two people in line