0

I would like a container to do the following in python 2-7:

I need that container to behave like a queue: first in first out, I append to it objects and then get them in the same order "from the other end".

However I also need to be able to read up to 5 objects from the beginning of the queue without popping them, then if I don't need them anymore I will pop them from the queue.

I am new to python and I need to know is there any container that would act as such? Or any easy simple implementation for it?

0

2 Answers 2

3

I'm fairly certain you want a deque from the collections module. It includes (among other things) append, pop, pop_left, and rotate methods, and also supports indexing. Indexing slows toward the middle, but is fast at the ends.

Sign up to request clarification or add additional context in comments.

2 Comments

With deque I will have to popleft then appendleft, is there a container I can access through indexing like a list, and would behave like deque? I am looking for that if available it would be faster, thank you though
"and also supports indexing". for instance, my_deque[3] is the 4th element.
1

See this module from the standard library. It should provide you with everything you want.

http://my.safaribooksonline.com/book/programming/python/9780132778633/data-structures/ch02lev1sec5

import Queue

q = Queue.Queue()

for i in range(5):
    q.put(i)

while not q.empty():
    print q.get(),
print

1 Comment

I bet you could subclass collections.deque to do what you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.