5.1.1. Using Lists as Stacks
The list methods make it very-a list as a stack, where the last element added is the first element retrieved ( "Last-in, first-out"). To add a item to the top of the stack, use append()
. To retrieve a item from the top of the stack, use pop()
without an explicit index. For example:
>>>
>>> stack = [3, 4, 5]>>> stack.append (6) >>> Stack.append (7) >>> stack[3, 4, 5, 6, 7]> ;>> Stack.pop () 7>>> stack[3, 4, 5, 6]>>> stack.pop () 6>>> stack.pop () 5>>> Stack[3, 4]
5.1.2. Using Lists as Queues
It is also possible to use a list as a queue, where the first element added is the first element retrieved ("First-in, fir St-out "); However, lists is not the efficient for this purpose. While appends and POPs from the end of the list was fast, doing inserts or POPs from the beginning of a list is slow (because All of the other elements has to be shifted by one).
To implement a queue, use collections.deque
which is designed to has fast appends and POPs from both ends. For example:
>>>
>>> from collections import deque>>> queue = Deque (["Eric", "John", "Michael"]) >>> Queue.append ("Terry") # Terry Arrives>>> queue.append ("Graham") # Graham Arrives>>> Queue.popleft () # The first to arrive now leaves ' Eric ' >>> queue.popleft () # The second-arrive now Leav Es ' John ' >>> queue # Remaining queue in order of Arrivaldeque ([' Michael ', ' Terry ', ' Graham '])
Python stacks and queues (implemented using list)