Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting last n items from queue

Tags:

python

queue

everything I see is about lists but this is about events = queue.queue() which is a queue with objects that I want to extract, but how would I go about getting the last N elements from that queue?

like image 234
entercaspa Avatar asked Jul 26 '16 12:07

entercaspa


2 Answers

By definition, you can't.

What you can do is use a loop or a comprehension to get the first (you can't get from the end of a queue) N elements:

N = 2
first_N_elements = [my_queue.get() for _ in range(N)]
like image 196
DeepSpace Avatar answered Sep 18 '22 23:09

DeepSpace


If you're multi-threading, "the last N elements from that queue" is undefined and the question doesn't make sense.

If there is no multi-threading, it depends on whether you care about the other elements (not the last N).

If you don't:

for i in range(events.qsize() - N):
    events.get()

after that, get N items

If you don't want to throw away the other items, you'll just have to move everything to a different data structure (like a list). The whole point of a queue is to get things in a certain order.

like image 27
beauxq Avatar answered Sep 21 '22 23:09

beauxq