Skip to the content

Stacks

Python · Unit 24: Data structures

A stack is a tower of plates: you put one on top and you take the top one off. The last one in is the first one out.

You don't need anything new: a list with append to put and pop() to take is already a stack.

plates = []
plates.append("red")
plates.append("blue")
print(plates.pop())

Prints

blue

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Complete the code

    Take the top plate off. It should print: blue

  3. 3. Predict the output

    What does this code print?

  4. 4. Find the bug

    undo should return the last action that was taken. Which line has the error?

  5. 5. Put the lines in order

    Put rewind(steps, times) together; it removes the latest actions and returns the ones left.

  6. 6. Find the case that fails

    top(stack) should return the item on top, or the text "-" if the stack is empty. Which call breaks it?

  7. 7. Predict the output

    Only the even numbers go onto the stack. What does it print?

  8. 8. Multiple choice

    What does this code do?

  9. 9. Predict the output

    The browser's "back" button. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →