---
description: What is Python Queue? A queue is a container that holds data. The data that is entered first will be removed first, and hence a queue is also called &quot;First in First Out&quot; (FIFO). The queue has two ends
title: "Python Queue: FIFO, LIFO Example"
image: https://www.guru99.com/images/python-queue-fifo-lifo.png
---

[Skip to content](#main)

**⚡ Smart Summary**

Python queue is a linear data structure that stores items and releases them in a defined order. The queue module provides FIFO, LIFO, and priority variants for managing tasks, buffering data, and coordinating work between threads safely.

- 🔢 **FIFO:** The Queue class removes the oldest item first, ideal for task scheduling and buffering.
- 🔁 **LIFO:** The LifoQueue class removes the newest item first, behaving like a stack.
- 📦 **Core methods:** put(), get(), qsize(), empty(), and full() manage items and report queue state.
- 🧵 **Thread-safe:** The queue module handles locking, so multiple threads can share one queue safely.
- 🎯 **Priority:** PriorityQueue releases items by priority rather than by insertion order.
- 🤖 **AI help:** AI assistants generate queue code and explain FIFO and LIFO trade-offs from a plain prompt.

Read More

![Python Queue FIFO LIFO](https://www.guru99.com/images/python-queue-fifo-lifo.png)

## What is Python Queue?

A queue is a container that holds data. The data that is entered first will be removed first, and hence a queue is also called “First in First Out” (FIFO). The queue has two ends front and rear. The items are entered from the rear and removed from the front side.

## How does Python Queue Work?

The queue can be easily compared with the real-world example the line of people waiting in a queue at the ticket counter, the person standing first will get the ticket first, followed by the next person and so on. The same logic goes for the queue data structure too.

Here is a diagrammatic representation of queue:

[![Python Queue Work]()](https://www.guru99.com/images/1/020820_0702_PythonQueue1.png)

The **Rear** represents the point where the items are inserted inside the queue. In this example, 7 is value for that.

The **Front** represents the point where the items from the queue will be removed. If you remove an item from the queue, the first element you will get is 1, as shown in the figure.

Item 1 was the first one to be inserted in the queue, and while removing it is the first one to come out. Hence the queue is called FIRST IN FIRST OUT (FIFO)

[![Python Queue Work]()](https://www.guru99.com/images/1/020820_0702_PythonQueue2.png)

In a queue, the items are removed in order and cannot be removed from in between. You just cannot remove the item 5 randomly from the queue, to do that you will have to remove all the items before 5. The items in queue will be removed in the order they are inserted.

## Types of Queue in Python

There are mainly two types of queue in Python:

- First in First out Queue: For this, the element that goes first will be the first to come out.To work with FIFO, you have to call **Queue()** class from queue module.
- Last in First out Queue: Over here, the element that is entered last will be the first to come out.To work with LIFO, you have to call **LifoQueue()** class from the queue module.

## Python queue Installation

It is very easy to work with queue in python. Here are the steps to follow to make use of queue in your code.

**Step 1)** You just have to import the queue module, as shown below:

```
import queue

```

The module is available by default with python, and you don’t need any additional installation to start working with the queue. There are 2 types of queue FIFO (first in first out) and LIFO (last in first out).

**Step 2)** To work with FIFO queue , call the Queue class using the queue module imported as shown below:

```
import queue
q1 = queue.Queue()

```

**Step 3)** To work with LIFO queue call the LifoQueue() class as shown below:

```
import queue
q1 = queue.LifoQueue()

```

## Methods available inside Queue and LifoQueue class

Following are the important methods available inside Queue and LifoQueue class:

- **put(item):** This will put the item inside the queue.
- **get():** This will return you an item from the queue.
- **empty():** It will return true if the queue is empty and false if items are present.
- **qsize():** returns the size of the queue.
- **full():** returns true if the queue is full, otherwise false.

**Don't Miss:**

- [Python Variables: How to Define/Declare String Variable Types](https://www.guru99.com/variables-in-python.html)
- [Python calendar Module with Example](https://www.guru99.com/calendar-in-python.html)
- [Import module in Python with Examples](https://www.guru99.com/import-module-python.html)
- [Python String split(): List, By Character, Delimiter](https://www.guru99.com/python-string-split.html)

## First In First Out Queue Example

In the case of first in first out, the element that goes first will be the first to come out.

### Add and item in a queue

Let us work on an example to add an item in a queue. To start working with the queue, first import the module queue, as shown in the example below.

To add an item , you can make use of put() method as shown in the example:

```
import queue
q1 = queue.Queue()
q1.put(10) #this will additem 10 to the queue.

```

By default, the size of the queue is infinite and you can add any number of items to it. In case you want to define the size of the queue the same can be done as follows

```
import queue
q1 = queue.Queue(5) #The max size is 5.
q1.put(1)
q1.put(2)
q1.put(3)
q1.put(4)
q1.put(5)
print(q1.full()) # will return true.

```

**Output:**

```
True

```

Now the size of the queue is 5, and it will not take more than 5 items, and the method q1.full() will return true. Adding any more items will not execute the code any further.

### Remove an item from the queue

To remove an item from the queue, you can use the method called get(). This method allows items from the queue when called.

The following example shows how to remove an item from the queue.

```
import queue
q1 = queue.Queue()
q1.put(10)

item1 = q1.get()

print('The item removed from the queue is ', item1)

```

**Output:**

```
The item removed from the queue is  10

```

## Last In First Out queue Example

In the case of last in the first out queue, the element that is entered last will be the first to come out.

To work with LIFO, i.e., last in the first out queue, we need to import the queue module and make use of the LifoQueue() method.

### Add and item in a queue

Here we will understand how to add an item to the LIFO queue.

```
import queue
q1 = queue.LifoQueue()
q1.put(10)

```

You have to use the put() method on LifoQueue, as shown in the above example.

### Remove an item from the queue

To remove an item from the LIFOqueue you can make use of get() method .

```
import queue
q1 = queue.LifoQueue()
q1.put(10)

item1 = q1.get()

print('The item removed from the LIFO queue is ', item1)

```

**Output:**

```
The item removed from the LIFO queue is  10

```

## Add more than 1 item in a Queue

In the above examples, we have seen how to add a single item and remove the item for FIFO and LIFOqueue. Now we will see how to add more than one item and also remove it.

### Add and item in a FIFOqueue

```
import queue
q1 = queue.Queue()

for i in range(20):
    q1.put(i) # this will additem from 0 to 20 to the queue

```

### Remove an item from the FIFOqueue

```
import queue
q1 = queue.Queue()

for i in range(20):
    q1.put(i) # this will additem from 0 to 20 to the queue

while not q1.empty():
print("The value is ", q1.get()) # get() will remove the item from the queue.

```

**Output:**

```
The value is  0
The value is  1
The value is  2
The value is  3
The value is  4
The value is  5
The value is  6
The value is  7
The value is  8
The value is  9
The value is  10
The value is  11
The value is  12
The value is  13
The value is  14
The value is  15
The value is  16
The value is  17
The value is  18
The value is  19

```

### Add and item in a LIFOqueue

```
import queue
q1 = queue.LifoQueue()
for i in range(20):
    q1.put(i) # this will additem from 0 to 20 to the queue

```

### Remove an item from the LIFOqueue

```
import queue
q1 = queue.LifoQueue()

for i in range(20):
    q1.put(i) # this will additem from 0 to 20 to the queue

while not q1.empty():
print("The value is ", q1.get()) # get() will remove the item from the queue.
```

**Output:**

```
The value is  19
The value is  18
The value is  17
The value is  16
The value is  15
The value is  14
The value is  13
The value is  12
The value is  11
The value is  10
The value is  9
The value is  8
The value is  7
The value is  6
The value is  5
The value is  4
The value is  3
The value is  2
The value is  1
The value is  0 

```

## Sorting Queue

Following example shows the queue sorting.The algorithm used for sorting is bubble sort.

```
import queue
q1 = queue.Queue()
#Addingitems to the queue
q1.put(11)
q1.put(5)
q1.put(4)
q1.put(21)
q1.put(3)
q1.put(10)

#using bubble sort on the queue
n =  q1.qsize()
for i in range(n):
    x = q1.get() # the element is removed
    for j in range(n-1):
        y = q1.get() # the element is removed
        if x > y :  
            q1.put(y)   #the smaller one is put at the start of the queue
        else:
            q1.put(x)  # the smaller one is put at the start of the queue
            x = y     # the greater one is replaced with x and compared again with nextelement
    q1.put(x)

while (q1.empty() == False): 
print(q1.queue[0], end = " ")  
        q1.get()

```

**Output:**

```
3 4 5 10 11 21

```

## Reversing Queue

To reverse the queue, you can make use of another queue and recursion.

The following example shows how to get the queue reversed.

Example:

```
import queue
q1 = queue.Queue()

q1.put(11)
q1.put(5)
q1.put(4)
q1.put(21)
q1.put(3)
q1.put(10)

def reverseQueue (q1src, q2dest) :  
    buffer = q1src.get()
    if (q1src.empty() == False) :
reverseQueue(q1src, q2dest)      #using recursion
    q2dest.put(buffer)
return q2dest

q2dest = queue.Queue()
qReversed = reverseQueue(q1,q2dest)

while (qReversed.empty() == False): 
print(qReversed.queue[0], end = " ")  
        qReversed.get()

```

**Output:**

```
10 3 21 4 5 11

```

## FAQs

🔀 What is the difference between a queue and a stack in Python?

A queue is FIFO, so the oldest item leaves first, while a stack is LIFO, where the newest item leaves first. Python’s queue module offers Queue for FIFO behavior and LifoQueue for stack behavior.

🧵 Is the Python queue module thread-safe?

Yes. Queue, LifoQueue, and PriorityQueue are built for multi-threaded programs and handle locking internally, so many producer and consumer threads can share one queue without race conditions or corrupted data.

📥 What is the difference between queue.Queue and collections.deque?

queue.Queue is thread-safe and designed for producer-consumer threading. collections.deque is a faster general-purpose double-ended queue for single-threaded code, supporting fast appends and pops from both ends.

⚡ What is a PriorityQueue in Python?

A PriorityQueue releases items in priority order instead of insertion order. You put (priority, data) tuples, and get() returns the lowest priority number first, which suits schedulers and shortest-path algorithms.

🚫 What happens when you call get() on an empty queue?

By default get() blocks and waits until an item is available. Pass block=False or use get\_nowait() to raise the queue.Empty exception immediately instead of waiting for a new item.

📏 How do you limit the size of a Python queue?

Pass maxsize to the constructor, for example queue.Queue(5). When the queue is full, put() blocks until space frees up and full() returns True. A maxsize of 0 means an unlimited queue.

🤖 How can AI tools help you work with Python queues?

AI assistants generate producer-consumer queue code, explain FIFO versus LIFO trade-offs, and suggest whether queue.Queue, deque, or asyncio.Queue fits your case. They also help spot deadlocks and missing task\_done() calls.

🧑‍💻 Can GitHub Copilot write Python queue and threading code?

Yes. GitHub Copilot autocompletes Queue setup, put() and get() loops, and worker threads from a comment. Agentic AI tools go further, refactoring blocking code to asyncio.Queue and adding error handling across a file.

#### Summarize this post with:

ChatGPTPerplexityGrokGoogle AI

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.**

##### Sign up for the newsletter

Subscribe for Free

You have successfully subscribed.  
Please check your inbox.

![AI-Newsletter]() Chosen by over **350,000+** professionals

[Scroll to top](#wrapper)

×

Search for:

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/python-queue-fifo-lifo.png","url":"https://www.guru99.com/images/python-queue-fifo-lifo.png","width":"700","height":"250","caption":"Python Queue (FIFO, LIFO)","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/python-queue-example.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/python","name":"Python"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/python-queue-example.html","name":"Python Queue: FIFO, LIFO Example"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/python-queue-example.html#webpage","url":"https://www.guru99.com/python-queue-example.html","name":"Python Queue: FIFO, LIFO Example","dateModified":"2026-10-07T13:38:45+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/python-queue-fifo-lifo.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/python-queue-example.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/editorial","name":"Editorial Team","url":"https://www.guru99.com/author/editorial","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/favicon-new-logo.png","url":"https://www.guru99.com/images/favicon-new-logo.png","caption":"Editorial Team","inLanguage":"en-US"},"sameAs":["https://www.guru99.com/editorial-team"],"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Python","headline":"Python Queue: FIFO, LIFO Example","description":"What is Python Queue? A queue is a container that holds data. The data that is entered first will be removed first, and hence a queue is also called &quot;First in First Out&quot; (FIFO). The queue has two ends","keywords":"python","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/editorial","name":"Editorial Team"},"dateModified":"2026-10-07T13:38:45+05:30","image":{"@id":"https://www.guru99.com/images/python-queue-fifo-lifo.png"},"copyrightYear":"2026","name":"Python Queue: FIFO, LIFO Example","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is the difference between a queue and a stack in Python?","acceptedAnswer":{"@type":"Answer","text":"A queue is FIFO, so the oldest item leaves first, while a stack is LIFO, where the newest item leaves first. Python's queue module offers Queue for FIFO behavior and LifoQueue for stack behavior."}},{"@type":"Question","name":"Is the Python queue module thread-safe?","acceptedAnswer":{"@type":"Answer","text":"Yes. Queue, LifoQueue, and PriorityQueue are built for multi-threaded programs and handle locking internally, so many producer and consumer threads can share one queue without race conditions or corrupted data."}},{"@type":"Question","name":"What is the difference between queue.Queue and collections.deque?","acceptedAnswer":{"@type":"Answer","text":"queue.Queue is thread-safe and designed for producer-consumer threading. collections.deque is a faster general-purpose double-ended queue for single-threaded code, supporting fast appends and pops from both ends."}},{"@type":"Question","name":"What is a PriorityQueue in Python?","acceptedAnswer":{"@type":"Answer","text":"A PriorityQueue releases items in priority order instead of insertion order. You put (priority, data) tuples, and get() returns the lowest priority number first, which suits schedulers and shortest-path algorithms."}},{"@type":"Question","name":"What happens when you call get() on an empty queue?","acceptedAnswer":{"@type":"Answer","text":"By default get() blocks and waits until an item is available. Pass block=False or use get_nowait() to raise the queue.Empty exception immediately instead of waiting for a new item."}},{"@type":"Question","name":"How do you limit the size of a Python queue?","acceptedAnswer":{"@type":"Answer","text":"Pass maxsize to the constructor, for example queue.Queue(5). When the queue is full, put() blocks until space frees up and full() returns True. A maxsize of 0 means an unlimited queue."}},{"@type":"Question","name":"How can AI tools help you work with Python queues?","acceptedAnswer":{"@type":"Answer","text":"AI assistants generate producer-consumer queue code, explain FIFO versus LIFO trade-offs, and suggest whether queue.Queue, deque, or asyncio.Queue fits your case. They also help spot deadlocks and missing task_done() calls."}},{"@type":"Question","name":"Can GitHub Copilot write Python queue and threading code?","acceptedAnswer":{"@type":"Answer","text":"Yes. GitHub Copilot autocompletes Queue setup, put() and get() loops, and worker threads from a comment. Agentic AI tools go further, refactoring blocking code to asyncio.Queue and adding error handling across a file."}}]}],"@id":"https://www.guru99.com/python-queue-example.html#schema-1140320","isPartOf":{"@id":"https://www.guru99.com/python-queue-example.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/python-queue-example.html#webpage"}}]}
```
