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: remove takes a value, pop takes an optional index (bag.pop(0) removes the first item).

Assignment

Starting with backpack = ["rope", "map", "lantern"], do these steps in order:

  1. Append "compass" to the end.
  2. Insert "snack" at the very front (index 0).
  3. Remove "map".
  4. Pop the last item and store it in a variable named dropped.
  5. Sort the backpack alphabetically.

The prints at the bottom should show ['lantern', 'rope', 'snack'] and compass.