Use lists as a stack or queue
#Using Lists as Stacks
"" "The list methods make it very easy to use 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. ""
stack = [3, 4, 5]
Stack.append (6)
Stack.append (7)
Print (Stack)
Stack.pop ()
Print (Stack)
Stack.pop ()
Stack.pop ()
Print (Stack)
#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, first-out"); However, lists is not the efficient for this purpose.
While appends and POPs from the end of 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). "" "
From collections Import Deque
Queue = Deque (["Eric", "John", "Michael"])
Queue.append ("Terry")
Queue.append ("Graham")
Queue.popleft ()
Queue.popleft ()
Print (queue)
When used as a queue, you need to introduce collections.deque
Operation result :
D:\Python3.6.1\python.exe f:/python_workspace/tutorial/lists2.py
[3, 4, 5, 6, 7]
[3, 4, 5, 6]
[3, 4]
Deque ([' Michael ', ' Terry ', ' Graham '])
Process finished with exit code 0
Python Basic Learning (v)