Python Basic Learning (v)

Source: Internet
Author: User

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)

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.