Stack

class swpy.swds.request.Stack

Bases: object

A class that implements the stack data structure. You can apply this class to any data type, including dictionaries, lists, tuples, and others.

stack

A list that stores stack items.

Type

str

Methods Summary

push()

Adds an item to the top of the stack.

pop()

Removes and returns the top item from the stack if it is not empty.

is_empty()

Checks if the stack is empty.

size()

Returns the number of items in the stack.

Methods Documentation

push(self, item)

Adds an item to the top of the stack. Due to the nature of stacks, the item added most recently will always be the first one to be removed by a pop operation, maintaining this order until the item added by push is removed. The push function can add an item of any data type to the stack.

Parameters
  • item ( str ) – Item to be added to the stack.

pop(self)

Removes and returns the top item from the stack if it is not empty. If the stack is empty, it returns None. This is a basic safety mechanism to prevent errors. After a pop function call, the state of the stack changes. The topmost item is removed, causing the size of the stack to decrease by one.

Returns

  • 'Top item' if the stack is not empty
  • peek(self)

    Returns the top item from the stack without removing it if it is not empty. If the stack is empty, it returns None. This is a basic safety mechanism to prevent errors. The peek function returns the top item of the stack in constant time O(1), regardless of the stack's size. This means it operates very quickly, independent of how many items are in the stack.

    Returns

  • 'Top item' if the stack is not empty
  • is_empty(self)

    Checks if the stack is empty. If the stack is empty, it returns True; if it's not empty, it returns False.

    Returns

  • bool – True/False (Success/Fail)
  • size(self)

    The size function uses the built-in len function to calculate the number of items currently stored in the stack.

    Returns

  • int - The number of items stored in the stack