
Code
Pack the Backpack
A list holds many values in order, inside square brackets.
bag = ["rope", "map"]
print(bag[0]) # rope (first item is index 0)
print(bag[-1]) # map (negative = from the end)
print(len(bag)) # 2
Lists can change. These methods edit the list in place:
| Code | What it does |
|---|---|
bag.append("gem") |
add to the end |
bag.insert(0, "gem") |
add at a position |
bag.remove("map") |
remove the first "map" |
item = bag.pop() |
remove the last item and give it back |
bag.sort() |
sort A to Z (or small to big) |
bag[1] = "net" |
replace the item at index 1 |
Pip tip:
removetakes a value,poptakes an optional index (bag.pop(0)removes the first item).
Assignment
Starting with backpack = ["rope", "map", "lantern"], do these steps
in order:
- Append
"compass"to the end. - Insert
"snack"at the very front (index0). - Remove
"map". - Pop the last item and store it in a variable named
dropped. - Sort the backpack alphabetically.
The prints at the bottom should show ['lantern', 'rope', 'snack']
and compass.
Starting with backpack = ["rope", "map", "lantern"], do these steps
in order:
- Append
"compass"to the end. - Insert
"snack"at the very front (index0). - Remove
"map". - Pop the last item and store it in a variable named
dropped. - Sort the backpack alphabetically.
The prints at the bottom should show ['lantern', 'rope', 'snack']
and compass.
main.py Python sleeping
Press Run to try your code, then Check to test it.