Skip to content

stack

A simple LIFO stack container with optional maximum capacity.

Stack(maxsize=0)

A simple LIFO stack container with optional maximum capacity.

The stack follows the Last-In, First-Out (LIFO) principle.

The most recently pushed item is returned by get() or removed by pop().

A maximum size can optionally be specified.
A maxsize of 0 means that the stack has no size limit.

Example:

stack = Stack(3)

stack.push("first")
stack.push("second")

stack.get()
# 'second'

stack.pop()
# 'second'

len(stack)
# 1

Args:
maxsize: Maximum number of items allowed in the stack.
0 means unlimited capacity.

Raises:
TypeError: If maxsize is not an integer.
ValueError: If maxsize is negative.

Capacity

maxsize property writable

Return the maximum number of items allowed in the stack.

Returns:
Maximum stack capacity. 0 means unlimited capacity.

Operations

Adding and Removing Items

push(value)

Push an item onto the top of the stack.

Args:
value: Value to push onto the stack.

Raises:
StackOverflowError: If the stack has reached its maximum capacity.

put(value)

Alias for push().

pop()

Remove and return the item at the top of the stack.

Returns:
The most recently pushed item.

Raises:
StackUnderflowError: If the stack is empty.

clear()

Remove all items from the stack.

Inspecting the Stack

get()

Return the item at the top of the stack without removing it.

Returns:
The most recently pushed item.

Raises:
StackUnderflowError: If the stack is empty.

peek()

Alias for get().

empty()

Return whether the stack is empty.

Returns:
True if the stack contains no items, otherwise False.

full()

Return whether the stack has reached its maximum capacity.

An unlimited stack is never considered full.

Returns:
True if the stack is full, otherwise False.

__len__()

Return the number of items currently in the stack.

__bool__()

Return whether the stack contains at least one item.

__contains__(value)

Return whether a value exists in the stack.

Args:
value: Value to search for.

Returns:
True if value is present, otherwise False.

__repr__()

Return the developer-oriented representation of the stack.

Iteration

__iter__()

Iterate over the items in the stack from top to bottom.

The most recently pushed item is yielded first, followed by the remaining items in reverse order of insertion.

Returns:
An iterator over the stack's items.

__reversed__()

Iterate over the items in the stack from bottom to top.

Exceptions

StackOverflowError

Bases: OverflowError

Raised when attempting to push an item onto a full stack.

StackUnderflowError

Bases: IndexError

Raised when attempting to access or remove an item from an empty stack.