All courses › Intermediate Programming › Stack and queue

Stack and queue

A stack follows LIFO: last in, first out, like a pile of plates. A queue follows FIFO: first in, first out. A Python list can be used as a stack with append/pop, while collections.deque is better suited as a queue.

Stack: LIFO\text{Stack: LIFO}append/pop at the same end
Queue: FIFO\text{Queue: FIFO}add at one end, remove at the other

Example

s = []; s.append(1); s.append(5); s.pop()

s.append(4); s.pop(); s.append(9)

Now s = [1, 9].

.pop() with no argument always removes the last element — that is what makes the list a stack.
Practise algorithms and data structures for free →

← Recursion · Sorting and search →

Part of Intermediate Programming: Algorithms and data structures.