2/36
Part 1 of 8 · Last in, first outLearn and do
Last in, first out
Each stack in the samples is a Python list, with the outermost call first and the newest call at the end. A call is added at the end and removed from the end, so the list works as a stack:
stack = []
stack.append("main") # push
stack.append("load") # push
print(stack[-1]) # peek
print(stack.pop()) # pop
print(stack)
load
load
['main']
Here is the list after each step, drawn with its end on top:
main
append("main")mainload
append("load")mainload
stack[-1]reads loadmain
pop()returns loadA stack keeps things the way a pile of plates does. You add to the top and take from the top, so the last thing in is the first thing out. That rule is called LIFO, for last in, first out.
A stack has three operations:
- push puts an item on top:
append. - pop takes the top item off and returns it:
pop()with no index. - peek looks at the top without taking it:
stack[-1].
You don't need a special type for it in Python. A list already is a stack, as long as you only use its end.
In the editor, write replay(ops). Each op is a string, "push main", "pop" or "peek". Run them on one list, and return what each pop and peek gave back, in order.