Optimisation: use deque instead of pop(0)