Python stacks and queues (implemented using list)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.