how to print the element at front of a queue python 3?

16.3k views Asked by At

    import queue
    q = queue.Queue()
    q.put(5)
    q.put(7)

print(q.get()) removes the element at front of the queue. How do i print this element without removing it? Is it possible to do so?

1

There are 1 answers

0
Kristian On BEST ANSWER

The Queue object has a collections.deque object attribute. Please see the Python documentation on accessing elements of the deque in regards to efficiency. A list may be a better use-case if you need to access elements randomly.

import queue

if __name__ == "__main__":
    q = queue.Queue()
    q.put(5)
    q.put(7)

    """
    dir() is helpful if you don't want to read the documentation
    and just want a quick reminder of what attributes are in your object
    It shows us there is an attribute named queue in the Queue class
    """
    for attr in dir(q):
        print(attr)

    #Print first element in queue
    print("\nLooking at the first element")
    print(q.queue[0])

    print("\nGetting the first element")
    print(q.get())

    print("\nLooking again at the first element")
    print(q.queue[0])

Note: I have abbreviated the output from the dir iterator

>>>
put
put_nowait
qsize
queue
task_done
unfinished_tasks

Looking at the first element
5

Getting the first element
5

Looking again at the first element
7
>>>