Learning LibraryCore Coding LibraryKids

Changing lists: add to the end, serve from the front

A list doesn't have to stay the same. Orders arrive, orders get served. Two commands let a list grow at one end and shrink at the other.

The big idea

append() adds an item to the end of a list, and pop() removes an item and hands it back to you.

See it in code

1Start simple

append() adds one item to the end of a list. The dot connects the command to the list it changes:

python
line = ["cookie", "brownie"]
line.append("muffin")
print("In line:", line)
A new order joins the line:
In line: ['cookie', 'brownie', 'muffin']

The list had two items and now has three. The new one went to the back, like a real line.

2A step further

pop(0) takes out the item at position 0, the front of the line. It also hands that item back, so you can store it:

python
line = ["cookie", "brownie", "muffin"]
served = line.pop(0)
print("Now serving:", served)
print("Still waiting:", line)
Serving the first customer:
Now serving: cookie
Still waiting: ['brownie', 'muffin']

pop(0) did two things at once. It removed cookie from the list, and it gave cookie to the variable served.

3In the bakery

Put both together. A customer's order is appended to the back, then a loop serves from the front until nobody is left:

python
line = ["cookie", "brownie"]

order = input("What would you like? ").lower()
line.append(order)
print("In line:", line)

while len(line) > 0:
    served = line.pop(0)
    print("Ding ding! Now serving:", served)
print("The line is empty, time to bake more!")
A customer orders a croissant, then everyone gets served:
What would you like? Croissant
In line: ['cookie', 'brownie', 'croissant']
Ding ding! Now serving: cookie
Ding ding! Now serving: brownie
Ding ding! Now serving: croissant
The line is empty, time to bake more!

The croissant joined last and was served last. First come, first served, all from two small commands.

The same idea, everywhere

Games change lists constantly. Every tap of space adds a laser to a list. Every hit takes a brick out of one. A snake grows by adding a square to its body.

Try it yourself

Change line.pop(0) to line.pop() with nothing in the parentheses, and run it. Who gets served first now? Is that fair to the customers?

The common mistake

Writing line = "muffin" when you mean line.append("muffin"). The equals sign replaces the whole list with one word. append keeps what's there and adds one more.

What it unlocks

To find an item without removing it, use positions. To keep serving until a list is empty, you need a while loop. And for a list you look up by label, not position, meet dictionaries.

Older, or want more depth? Read the Teens version →