Home > Article > Backend Development > Is there a stack in python?
In the English dictionary, Stack means placing an object on top of another object. The way memory is allocated in this data structure is the same. It stores data elements in a similar way to a stack of dishes in the kitchen: one on top of the other. Therefore, the end of the stack data that allows operations can be called the top of the stack. Elements can be added to the top of the stack or simply removed from the stack.
In a stack, the last element in sequence will appear first because it can only be removed from the top of the stack. This functionality is called last-in-first-out (LIFO) functionality. The operations of adding and removing elements are called PUSH and POP. In the program below, we implement it as add and remove functions. First declare an empty list and use the append() and pop() methods to add and remove data elements.
Push into the stack
class Stack: def __init__(self): self.stack = [] def add(self, dataval):# Use list append method to add element if dataval not in self.stack: self.stack.append(dataval) return True else: return False# Use peek to look at the top of the stack def peek(self): return self.stack[0]AStack = Stack()AStack.add("Mon")AStack.add("Tue")AStack.peek()print(AStack.peek())AStack.add("Wed")AStack.add("Thu")print(AStack.peek())Python
Execute the above example code and get the following results-
Mon MonShell
Related recommendations: "python video tutorial》
Stack removal
Only data elements can be removed from the stack. A python program that can achieve this function is implemented below. The remove function in the following program returns the topmost element. First check the top element by calculating the size of the stack, then use the built-in pop() method to find out the topmost element. Refer to the following code implementation
class Stack: def __init__(self): self.stack = [] def add(self, dataval):# Use list append method to add element if dataval not in self.stack: self.stack.append(dataval) return True else: return False# Use list pop method to remove element def remove(self): if len(self.stack) <= 0: return ("No element in the Stack") else: return self.stack.pop()AStack = Stack()AStack.add("Mon")AStack.add("Tue")print(AStack.remove())AStack.add("Wed")AStack.add("Thu")print(AStack.remove())Python
Execute the above example code and get the following results
Tue Thu
The above is the detailed content of Is there a stack in python?. For more information, please follow other related articles on the PHP Chinese website!