collections Module
The collections module provides data structures for storing and manipulating collections of values.
Stack
A Last-In-First-Out (LIFO) data structure.
new_stack()
Creates and returns a new empty stack.
Returns:
Stack: A new empty stack.
Example:
push(item)
Adds an item to the top of the stack.
Parameters:
item: The item to add to the stack.
Example:
pop()
Removes and returns the top item from the stack.
Returns:
any: The top item, orNoneif the stack is empty.
Example:
peek()
Returns the top item without removing it.
Returns:
any: The top item, orNoneif the stack is empty.
Example:
is_empty()
Checks if the stack is empty.
Returns:
bool:trueif the stack is empty,falseotherwise.
Example:
size()
Returns the number of items in the stack.
Returns:
int: The number of items in the stack.
Example:
inspect()
Returns a string representation of the stack.
Returns:
string: A string representation of the stack.
Example:
Queue
A First-In-First-Out (FIFO) data structure.
new_queue()
Creates and returns a new empty queue.
Returns:
Queue: A new empty queue.
Example:
| Create Queue | |
|---|---|
enqueue(item)
Adds an item to the end of the queue.
Parameters:
item: The item to add to the queue.
Example:
dequeue()
Removes and returns the first item from the queue.
Returns:
any: The first item, orNoneif the queue is empty.
Example:
peek()
Returns the first item without removing it.
Returns:
any: The first item, orNoneif the queue is empty.
Example:
is_empty()
Checks if the queue is empty.
Returns:
bool:trueif the queue is empty,falseotherwise.
Example:
size()
Returns the number of items in the queue.
Returns:
int: The number of items in the queue.
Example:
inspect()
Returns a string representation of the queue.
Returns:
string: A string representation of the queue.
Example:
Complete Example
Draining a queue (while-style loop using for)
Harneet does not have a separate while keyword. Use a condition-only for loop to achieve the same effect (just like Go):
| While Loop Pattern | |
|---|---|