Stack¶
- class swpy.swds.request.Stack¶
Bases:
objectA class that implements the stack data structure. You can apply this class to any data type, including dictionaries, lists, tuples, and others.
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
popoperation, maintaining this order until the item added bypushis removed. Thepushfunction can add anitemof 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 apopfunction call, the state of the stack changes. The topmost item is removed, causing the size of the stack to decrease by one.- Returns
- 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. Thepeekfunction 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
- is_empty(self)¶
Checks if the stack is empty. If the stack is empty, it returns
True; if it's not empty, it returnsFalse.- Returns
bool – True/False (Success/Fail)
- size(self)¶
The
sizefunction 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