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?
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)]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With