The supply cart for the next mission keeps changing. Someone adds a radio, someone takes the last item off to pack it, and someone else wants the list in alphabetical order.
Rocket has been retyping the whole list every time. "There must be a quicker way," he says, flexing his tired fingers.
Raven points to the word supplies at the start of each line. "What do you notice?" she asks. "Every change is something you do to the list. Add to it. Take from it. Sort it."
Nova draws a dot after the word supplies and a menu of glowing actions. "I found a pattern," she says. "Lists come with their own tools, called methods. You reach them with a dot."
Rocket types supplies and a dot, and wonders what he will find.
| Method | What it does |
|---|---|
| supplies.append(x) | adds x to the end |
| supplies.pop() | removes the last item and gives it back |
| supplies.pop(0) | removes the first item and gives it back |
| supplies.sort() | puts the items in order (A to Z, or smallest first) |
| x in supplies | True if x is in the list (not a method, but very handy) |
# supplies.py
supplies = ["water", "tools", "maps"]
supplies.append("radio")
print(supplies)
last = supplies.pop()
print("Packed:", last)
print(supplies)
supplies.sort()
print(supplies)
print("maps" in supplies)
print(len(supplies)) ['water', 'tools', 'maps', 'radio'] Packed: radio ['water', 'tools', 'maps'] ['maps', 'tools', 'water'] True 3
Notice that append, pop and sort change the list itself. You do not write supplies = supplies.sort(); just supplies.sort() on its own line.
Two more methods are useful. The insert(i, x) method puts x at index i and moves the later items along. The remove(x) method takes away the first item equal to x.
pop uses a position, but remove uses the value itself.
# launch_steps.py
steps = ["fuel check", "weather check", "launch"]
steps.insert(2, "crew check")
print(steps)
steps.remove("weather check")
print(steps)
done = steps.pop(0)
print("Done:", done)
print(steps) ['fuel check', 'weather check', 'crew check', 'launch'] ['fuel check', 'crew check', 'launch'] Done: fuel check ['crew check', 'launch']
| Statement | True or false? |
|---|---|
| append always adds to the end of a list. | ? |
| remove takes away every copy of a value. | ? |
| pop(0) removes the first item. | ? |
| sort puts words in A to Z order. | ? |
You can now grow, shrink and sort lists. Tomorrow you will loop through a list and work with every item.