I've recently gotten into investigating how various data structures are implemented in Python in order to make my code more efficient. In investigating how lists and deques work, I found that I can get benefits when I want to shift and unshift reducing the time from O(n) in lists to O(1) in deques (lists being implemented as fixed-length arrays that have to be copied completely each time something is inserted at the front, etc...). What I can't seem to find are the specifics of how a deque is implemented, and the specifics of its downsides v.s. lists. Can someone enlighten me on these two questions?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
While, I am not exactly sure how Python has implemented it, here I wrote an implementation of Queues using only arrays. It has the same complexity as Python's Queues.
And here you can test it with some code:
It won't work as fast as the C implementation, but it uses the same logic.
In addition to all the other helpful answers, here is some more information comparing the time complexity (Big-Oh) of various operations on Python lists, deques, sets, and dictionaries. This should help in selecting the right data structure for a particular problem.
Check out
collections.deque
. From the docs:Just as it says, using pop(0) or insert(0, v) incur large penalties with list objects. You can't use slice/index operations on a
deque
, but you can usepopleft
/appendleft
, which are operationsdeque
is optimized for. Here is a simple benchmark to demonstrate this:Results on my machine:
https://hg.python.org/cpython/file/3.5/Modules/_collectionsmodule.c
So yes, a
deque
is a (doubly-)linked list as another answer suggests.Elaborating: What this means is that Python lists are much better for random-access and fixed-length operations, including slicing, while deques are much more useful for pushing and popping things off the ends, with indexing (but not slicing, interestingly) being possible but slower than with lists.
The documentation entry for
deque
objects spells out most of what you need to know, I suspect. Notable quotes:But...
I'd have to take a look at the source to tell whether the implementation is a linked list or something else, but it sounds to me as though a
deque
has roughly the same characteristics as a doubly-linked list.