Queue¶
py_ds.datastructures.queue.Queue
¶
Bases: Generic[T]
A simple FIFO (first-in, first-out) queue.
Backed by a Python list, providing O(1) enqueue and O(1) dequeue operations.
Initialize the queue.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
Iterable[T] | None
|
Optional iterable of initial items. The first item of the iterable becomes the front of the queue. |
None
|
Source code in src/py_ds/datastructures/queue.py
Functions¶
enqueue
¶
Add an item to the back of the queue.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
item
|
T
|
The item to add to the queue. |
required |
Time complexity: O(1).
dequeue
¶
Remove and return the front item of the queue.
Returns:
| Type | Description |
|---|---|
T
|
The item that was at the front of the queue. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the queue is empty. |
Time complexity: O(1).
Source code in src/py_ds/datastructures/queue.py
peek
¶
Return the front item without removing it.
Returns:
| Type | Description |
|---|---|
T
|
The item at the front of the queue. |
Raises:
| Type | Description |
|---|---|
IndexError
|
If the queue is empty. |
Time complexity: O(1).
Source code in src/py_ds/datastructures/queue.py
is_empty
¶
Check if the queue is empty.
Returns:
| Type | Description |
|---|---|
bool
|
True if the queue contains no items, False otherwise. |
Time complexity: O(1).
extend
¶
Enqueue multiple items in the order provided.
The first item of the iterable becomes the next after the current back.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
Iterable[T]
|
An iterable of items to enqueue. |
required |
Time complexity: O(k), where k is the number of items.
Source code in src/py_ds/datastructures/queue.py
clear
¶
Remove all items from the queue.
After this call, is_empty() returns True and len(queue) == 0.
Time complexity: O(1).
to_list
¶
Convert the queue to a Python list.
Returns:
| Type | Description |
|---|---|
list[T]
|
A shallow copy of the queue contents as a list, ordered from |
list[T]
|
front to back. |
Time complexity: O(n).
__len__
¶
Return the number of items in the queue.
Returns:
| Type | Description |
|---|---|
int
|
The number of items in the queue. |
Time complexity: O(1).
__bool__
¶
Return the truthiness of the queue.
Returns:
| Type | Description |
|---|---|
bool
|
False if the queue is empty, True otherwise. |
Enables: if queue: ...
__iter__
¶
Iterate over the items in the queue from front to back.
Yields:
| Type | Description |
|---|---|
T
|
Each item in the queue, starting from the front. |
Example
q = Queue([1, 2, 3]) list(q) # [1, 2, 3] (front to back)
Source code in src/py_ds/datastructures/queue.py
__repr__
¶
Return a string representation of the queue.
Returns:
| Type | Description |
|---|---|
str
|
A string representation showing the class name and queue contents. |
Example
Queue([1, 2, 3])