Python Basics: The use of deque

Source: Internet
Author: User

Deque (maxlen=n) creates a fixed-length queue that automatically moves except for the oldest record when a new record is added and the queue is full.

 1  from  collections import   deque  2  d=deque ( Maxlen=3)  3  d.append (1"  4  d.append (2 5  d.append (3 6  print   (d)  7  print   ( Type (d))  8  d.append (4 9  print  (d) 
View Code

The output is as follows:

Deque ([1, 2, 3], maxlen=3)
<class ' Collections.deque ' >
Deque ([2, 3, 4], maxlen=3)

Although the functionality of the deque can be accomplished through list operations (Append, Del), this solution to the queue is much more elegant and runs faster. If Deque does not specify a queue length, it will get a queue with no bounds and can perform add and eject operations at both ends, for example:

1  fromCollectionsImportdeque2D=deque ()3D.append (1)4D.append (2)5D.append (3)6 Print(d)7D.appendleft (4)8 Print(d)9 D.pop ()Ten Print(d) One D.popleft () A Print(d)
View Code

The output is as follows:

Deque ([1, 2, 3])
Deque ([4, 1, 2, 3])
Deque ([4, 1, 2])
Deque ([1, 2])

The complexity of adding or ejecting elements from both ends of the queue is O (1). This is different from the list, when inserting or removing elements from the head of the list, the complexity of the list is O (N)

Python Basics: The use of deque

Related Article

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.