Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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


    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?

like image 674
Ankit Jain Avatar asked Oct 20 '25 07:10

Ankit Jain


1 Answers

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
>>>
like image 86
Kristian Avatar answered Oct 22 '25 23:10

Kristian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!