python-the list as a stack, the queue uses

Source: Internet
Author: User

The list method makes it easy for a list to be used as a stack, a stack as a specific data structure, and the last element to be released (LIFO) in the first entry. append()you can add an element to the top of the stack by using a method. pop()an element can be freed from the top of the stack using a method that does not specify an 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.< span class= "n" >pop () 5>>> stack[3, 4] 
You can also use the list as a queue, the queue as a specific data structure, the first entry of the element is first released (FIFO). However, the list is inefficient in this way. Adding and popping up from the end of the list is relatively slow (because, for an element, you move all the elements in the entire list).
to implement the queue, use  collections.deque, which is designed for quick insertion and deletion at both ends. For example:
/span>
>>>FromCollectionsImportDeque>>>Queue=deque ([ "a"  "B"  "C" ]) >>> queueappend ( "A" )  >>> queue. Append ( "B" ) >>> span class= "n" >queue. Popleft () 
There is a way to delete a subkey: del  statement from the list by a given index instead of a value. It differs from the  pop ()   method with a return value. Statement  del  can also remove slices from the list or empty the entire list.

/span>

python-the list as a stack, the queue uses

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.