python stack example
In Python, you can use list to implement the stack. 1. Use append() to press the stack, 2. Use pop() to pop the stack, 3. View the top of the stack through the index [-1], 4. Use len() to determine whether it is empty, 5. Encapsulating the Stack class can improve the readability of the code. All operations are based on the end to ensure the O(1) time complexity, and are suitable for function calls, bracket matching, DFS, undo operations and other scenarios.
The stack in Python is a "last in first out" (LIFO, Last In First Out) data structure. Although Python does not have a special built-in Stack
type, we can easily implement the basic operations of the stack with list
: push and pop .

Here is a simple Python stack usage example:
✅ Use list to implement stack
# Create an empty stack = [] # push - use the append() method stack.append(10) stack.append(20) stack.append(30) print("Current stack:", stack) # Output: [10, 20, 30] #Pop-Use the pop() method (remove and return the last element) top_item = stack.pop() print("Popular element:", top_item) # Output: 30 print("Current stack:", stack) # Output: [10, 20] # View the top element of the stack (not deleted) if stack: print("top element:", stack[-1]) # Output: 20 # determine whether the stack is empty is_empty = len(stack) == 0 print("Stack is empty?", is_empty) # Output: False
?️ Summary of common stack operations
operate | method | illustrate |
---|---|---|
push(x) | stack.append(x) | Push element x to the top of the stack |
pop() | stack.pop() | Remove and return the top element of the stack. An error will be reported when the stack is empty. |
peek/top() | stack[-1] | View the top element of the stack without removing it |
is_empty() | len(stack) == 0 | Determine whether the stack is empty |
size() | len(stack) | Get the number of elements in the stack |
⚠️ Note: When using
pop()
, make sure that the stack is not empty, otherwiseIndexError
will be thrown. You can first determine whether it is empty.
✅ Safer stack operation (with empty check)
def safe_pop(stack): if not stack: print("Stack is empty, element cannot be popped") return None return stack.pop() def safe_peek(stack): if not stack: print("Stack is empty, no top element") return None return stack[-1] # Example stack = [1, 2, 3] print(safe_peek(stack)) # Output: 3 print(safe_pop(stack)) # Output: 3 print(safe_pop(stack)) # Output: 2 print(stack) # Output: [1] print(safe_pop(stack)) # Output: 1 print(safe_pop(stack)) # Output: The stack is empty, element cannot be popped
? Optional: Encapsulate a Stack class
If you want the code to be clearer and more object-oriented, you can encapsulate a Stack
class:
class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): if not self.is_empty(): return self.items.pop() raise IndexError("pop from empty stack") def peek(self): if not self.is_empty(): return self.items[-1] raise IndexError("peek from empty stack") def is_empty(self): return len(self.items) == 0 def size(self): return len(self.items) def __str__(self): return str(self.items) # Use examples s = Stack() s.push(1) s.push(2) s.push(3) print("stack:", s) # [1, 2, 3] print("top:", s.peek()) # 3 print("pop:", s.pop()) # 3 print("Stack Size:", s.size()) # 2
? Practical application scenarios
- Function call stack (automatic maintenance of the system)
- Expression evaluation (such as bracket matching)
- Depth First Search (DFS)
- Undo function
- Browser's Back button
Basically that's it. Use list
to achieve simple and efficient stack, suitable for most scenarios. As long as you are careful not to insert/delete in the middle, and only at the end of the operation, you can ensure the O(1) time complexity.

The above is the detailed content of python stack example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Yes,aPythonclasscanhavemultipleconstructorsthroughalternativetechniques.1.Usedefaultargumentsinthe__init__methodtoallowflexibleinitializationwithvaryingnumbersofparameters.2.Defineclassmethodsasalternativeconstructorsforclearerandscalableobjectcreati

In Python, using a for loop with the range() function is a common way to control the number of loops. 1. Use when you know the number of loops or need to access elements by index; 2. Range(stop) from 0 to stop-1, range(start,stop) from start to stop-1, range(start,stop) adds step size; 3. Note that range does not contain the end value, and returns iterable objects instead of lists in Python 3; 4. You can convert to a list through list(range()), and use negative step size in reverse order.

To get started with quantum machine learning (QML), the preferred tool is Python, and libraries such as PennyLane, Qiskit, TensorFlowQuantum or PyTorchQuantum need to be installed; then familiarize yourself with the process by running examples, such as using PennyLane to build a quantum neural network; then implement the model according to the steps of data set preparation, data encoding, building parametric quantum circuits, classic optimizer training, etc.; in actual combat, you should avoid pursuing complex models from the beginning, paying attention to hardware limitations, adopting hybrid model structures, and continuously referring to the latest documents and official documents to follow up on development.

The key to using Python to call WebAPI to obtain data is to master the basic processes and common tools. 1. Using requests to initiate HTTP requests is the most direct way. Use the get method to obtain the response and use json() to parse the data; 2. For APIs that need authentication, you can add tokens or keys through headers; 3. You need to check the response status code, it is recommended to use response.raise_for_status() to automatically handle exceptions; 4. Facing the paging interface, you can request different pages in turn and add delays to avoid frequency limitations; 5. When processing the returned JSON data, you need to extract information according to the structure, and complex data can be converted to Data

Python's onelineifelse is a ternary operator, written as xifconditionelsey, which is used to simplify simple conditional judgment. It can be used for variable assignment, such as status="adult"ifage>=18else"minor"; it can also be used to directly return results in functions, such as defget_status(age):return"adult"ifage>=18else"minor"; although nested use is supported, such as result="A"i

This article has selected several top Python "finished" project websites and high-level "blockbuster" learning resource portals for you. Whether you are looking for development inspiration, observing and learning master-level source code, or systematically improving your practical capabilities, these platforms are not to be missed and can help you grow into a Python master quickly.

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.

Use Seaborn's jointplot to quickly visualize the relationship and distribution between two variables; 2. The basic scatter plot is implemented by sns.jointplot(data=tips,x="total_bill",y="tip",kind="scatter"), the center is a scatter plot, and the histogram is displayed on the upper and lower and right sides; 3. Add regression lines and density information to a kind="reg", and combine marginal_kws to set the edge plot style; 4. When the data volume is large, it is recommended to use "hex"
