Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →A Python stack is usually just a list used from its right-hand end: call append() to push and pop() (without an index) to remove the most recently added item. Both operations are O(1) for CPython lists at that end. Choose collections.deque when you also need efficient operations on the left end, or wrap either container when you need a restricted, domain-specific API.
What a stack is
A stack is a last-in, first-out (LIFO) data structure. The newest item is the first one removed, like a pile of plates: you place a plate on top and take the top plate off first. Python’s tutorial explicitly describes list methods as an easy way to use a list as a stack, with append() adding to the top and pop() retrieving the top item.
The key design decision is which end represents the top. With a list, use the right-hand end:
stack.append(value)pushes.stack.pop()pops and returns the top value.stack[-1]peeks without removing the value.not stacktests whether the stack is empty.
Implementing a stack with a list
This is the smallest complete implementation:
stack = []
stack.append("first") # push
stack.append("second") # push
item = stack.pop() # "second"
print(item)
print(stack) # ["first"]
The values come out in reverse insertion order:
stack = []
for value in ("a", "b", "c"):
stack.append(value)
while stack:
print(stack.pop())
# c
# b
# a
Keep the top at the right. Python’s complexity reference lists append as O(1) and pop(k) as O(n-k); consequently, removing the final element with plain pop() is O(1). Those complexity figures describe CPython built-in types and can differ in another Python implementation. See the Python time-complexity reference.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
#1 Best Overall
- Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
- Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
- Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
- Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
- 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.
Peeking and checking emptiness
if stack:
top = stack[-1]
print(f"Next item: {top}")
else:
print("The stack is empty")
Do not use stack[-1] without deciding what an empty stack should mean. Indexing an empty list raises IndexError.
Handling an empty stack
Calling pop() on an empty list raises IndexError: pop from empty list. You have three reasonable policies:
Check before removal
if stack:
value = stack.pop()
else:
value = None
This is appropriate when “no item” is a normal outcome and None cannot be confused with a real stored value.
Let the exception signal a programming error
value = stack.pop() # raises IndexError if empty
This keeps mistakes visible and preserves the container’s standard behavior.
Translate it in a wrapper
A public API can raise a domain-specific exception or return a sentinel. Document that contract; callers should not have to guess whether an empty pop returns None or raises.
Rank #2
- 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
- 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
- Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
- 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
- What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.
List versus collections.deque
collections.deque is a double-ended queue. Its documented operations include append, appendleft, pop, and popleft. It is the better fit when the same structure may need efficient operations at both ends or when a double-ended API is useful. For a one-ended stack, a list is direct and idiomatic.
| Question | List | deque |
|---|---|---|
| Push at top (right) | append; O(1) in CPython |
append |
| Pop at top (right) | pop(); O(1) in CPython |
pop() |
| Efficient left-end operations | No: insert(0, value) and pop(0) move elements and are O(n) |
appendleft and popleft |
| Best use | Simple LIFO abstraction | Potentially double-ended access |
| Documentation | Python list tutorial | collections documentation |
Do not emulate a stack by inserting and removing at index zero. CPython’s list representation must move the other elements, so those operations are O(n). That choice becomes costly as the stack grows.
from collections import deque
stack = deque()
stack.append("first")
stack.append("second")
print(stack.pop()) # second
Building a small stack class
A wrapper hides storage, prevents callers from mutating the backing container directly, and gives you one place to add validation or domain-specific errors. The following list-backed class exposes the common operations:
The Tool Desk
Outbyte PC Repair FREEClear out junk files and repair common Windows errorsFree Scan →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →class Stack:
def __init__(self):
self._items = []
def push(self, value):
self._items.append(value)
def pop(self):
return self._items.pop()
def peek(self):
return self._items[-1]
def is_empty(self):
return not self._items
def __len__(self):
return len(self._items)
s = Stack()
s.push("compile")
s.push("test")
assert s.peek() == "test"
assert len(s) == 2
assert s.pop() == "test"
assert not s.is_empty()
The method names are an API design choice; the underlying list primitives are the standard-library behavior. If you want a deque-backed implementation, replace self._items = [] with self._items = deque() and import deque. The methods used above remain available.
Adding explicit empty-stack behavior
You can preserve IndexError while making the message part of your own API:
Rank #3
- Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
- Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
- Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
- Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
- What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
class EmptyStackError(Exception):
pass
class SafeStack:
def __init__(self):
self._items = []
def push(self, value):
self._items.append(value)
def pop(self):
if not self._items:
raise EmptyStackError("cannot pop an empty stack")
return self._items.pop()
def peek(self):
if not self._items:
raise EmptyStackError("cannot peek at an empty stack")
return self._items[-1]
def __len__(self):
return len(self._items)
Use a custom exception when an empty stack is an expected domain condition that callers should handle distinctly. Otherwise, exposing IndexError keeps the wrapper simple.
Testing a stack implementation
Tests should verify LIFO order, peeking, length, emptiness, and the chosen empty behavior:
def test_stack():
s = Stack()
assert s.is_empty()
s.push(1)
s.push(2)
assert len(s) == 2
assert s.peek() == 2
assert s.pop() == 2
assert s.pop() == 1
assert s.is_empty()
def test_empty_pop_raises():
s = Stack()
try:
s.pop()
except IndexError:
pass
else:
raise AssertionError("pop should raise IndexError")
Also test values such as None, duplicate values, and a large number of pushes if your application has unusual validation or memory requirements. A stack stores references to objects; popping removes the reference from the container, but any other references to that object remain.
Common mistakes and troubleshooting
Using the wrong end
insert(0, value) and pop(0) still produce LIFO behavior if used consistently, but they incur O(n) movement. Switch to append and pop().
Peeking with pop()
pop() mutates the stack. Use stack[-1] (after an emptiness check) when you only need to inspect the top.
Rank #4
- Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
- Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
- Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
- Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
- Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft
Unexpected IndexError
Find every path that pops, including loops and exception handlers. Guard with if stack, or define and catch a wrapper exception. Avoid catching a broad Exception, which can hide unrelated bugs.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallCrashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteAccidentally exposing storage
If callers can access _items, they can bypass LIFO rules. Keep the attribute private by convention and expose only the methods your application needs.
Assuming complexity is universal
The O(1) statements above are for CPython’s documented built-in types. If portability to another Python implementation matters, check that implementation’s guarantees rather than treating CPython behavior as a language-wide promise.
Performance, reliability, and design choices
- Choose a list when the abstraction is strictly push/pop at one end and a minimal dependency-free implementation is desirable.
- Choose a deque when requirements include both ends now or may include them later.
- Wrap the container when you need validation, a stable interface, metrics, or a domain-specific empty-stack error.
- Keep operations at the top; random indexing or deleting from the middle is not stack behavior and may have different costs.
- Define ownership: decide whether the stack accepts any Python object or validates a particular type before pushing.
Neither the list nor deque examples provide an automatic cross-thread coordination policy. If multiple threads share a stack, define synchronization and ownership at the application level instead of assuming the wrapper makes compound sequences such as “check, then pop” indivisible.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Or skip the browser setup
If you need a clean image of a stack tutorial, API example, or generated documentation page for a report, ScreenshotNeo can capture the URL directly instead of configuring a browser. Its cleanup step accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. It also provides an MCP server for Claude, Cursor, and other MCP clients, with take_screenshot, get_page_info, and capture_pdf tools.
Do these 3 things before closing this tab:
1Clear out junk files and repair common Windows errors2Scan for outdated or missing drivers - takes under a minute3Repair Windows errors before they cause bigger problemsOne GET request is enough:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://docs.python.org/3.15/tutorial/datastructures.html -o shot.webp
See the ScreenshotNeo API documentation for all options. A free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots. Create a free ScreenshotNeo account.
Best Value
- 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
- Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
- Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
- HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
- What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.
Python, cURL, and Node.js examples
Python
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={
"access_key": "YOUR_API_KEY",
"url": "https://docs.python.org/3.15/tutorial/datastructures.html",
},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
Node.js
const q = new URLSearchParams({
access_key: 'YOUR_API_KEY',
url: 'https://docs.python.org/3.15/tutorial/datastructures.html'
});
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo supports PNG, JPEG, WebP, and PDF responses, plus options such as full-page capture, an element CSS selector, dark mode, device presets, custom viewport and retina scale, PDF paper and page ranges, custom CSS or JavaScript, click and wait conditions, blocked resources, headers, cookies, user agent, authorization, timezone, geolocation, transparent backgrounds, resizing, caching TTL, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, and a usage API. Every feature is available on every plan.
Quick decision checklist
- Is the top at the right-hand end?
- Do push and pop use
appendand plainpop()? - Is empty
pop/peekbehavior documented and tested? - Would efficient operations at both ends justify
deque? - Should callers be prevented from mutating the backing container?
- Are complexity claims qualified as CPython behavior where appropriate?
Frequently Asked Questions
Does Python have a built-in Stack class?
Python does not require a dedicated stack class for the common case; the tutorial recommends using list methods. A small wrapper is useful when you need a restricted or domain-specific API.
Can a stack contain duplicate values or None?
Yes. Lists and deques can store ordinary Python objects, including duplicates and None; your wrapper can add stricter validation if the application requires it.
Free tools Windows power users keep installed
One-click scans. No signup required.
When should I use queue.LifoQueue instead?
Use a concurrency-oriented queue type when your design needs coordinated producer and consumer operations. For a local, single-owner LIFO abstraction, list or deque is simpler.
The Bottom Line
For most Python stacks, use a list with append() and plain pop(). Use deque for double-ended needs, and wrap the container when your application requires a controlled API or explicit empty-stack errors.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

