1. Why You Need to Understand the Time Complexity of Containers
Python provides several commonly used containers:
list: a list that supports index access and dynamic insertion and deletion.tuple: a tuple that provides an immutable sequence.dict: a dictionary that provides a key-value mapping.set: a set that provides deduplication and efficient membership testing.frozenset: an immutable set.str: a string, an immutable sequence of characters.deque: a double-ended queue, suitable for efficient insertion and deletion at both ends.heapq: a heap operation tool implemented on top of a list.
These containers may overlap in functionality, but their underlying data structures and performance characteristics are not the same.
For example, both of the following operations can check whether an element exists:
# List membership test
numbers = [10, 20, 30, 40, 50]
print(30 in numbers)
# Set membership test
number_set = {10, 20, 30, 40, 50}
print(30 in number_set)
For small amounts of data, the difference between the two may not be obvious.
When the data scale expands to hundreds of thousands or even millions, the performance difference caused by the underlying data structure can become very obvious.
Therefore, understanding container performance requires answering three questions:
- How much work does a certain operation need to perform?
- As the data scale expands, how does the execution cost grow?
- Is there a data structure that is more suitable for the current scenario?
2. Time Complexity and Space Complexity
1. What Is Time Complexity
Time complexity describes how the execution workload of an algorithm changes as the input size grows.
Big O notation is usually used.
Assuming the input data size is n, common complexities are as follows:
| Complexity | Name | Growth Trend | Common Scenarios |
|---|---|---|---|
| O(1) | Constant time | Basically does not change with scale | List indexing, average hash lookup |
| O(\log n) | Logarithmic time | Grows slowly | Binary search, heap adjustment |
| O(n) | Linear time | Proportional to data scale | List traversal, linear search |
| O(n\log n) | Linearithmic time | Faster than linear growth | Efficient comparison sorting |
| O(n^2) | Quadratic time | Grows relatively fast | Double full traversal |
| O(2^n) | Exponential time | Grows extremely fast | Some exhaustive searches |
For example:
numbers = [10, 20, 30, 40, 50]
# O(1): access by index
value = numbers[2]
# O(n): traverse the entire list
for number in numbers:
print(number)
List index access does not need to look up elements one by one as the list length grows, whereas traversing a list requires processing every element in it.
2. What Is Space Complexity
Space complexity describes how the extra space required by an algorithm changes as the input size grows during execution.
For example:
numbers = [1, 2, 3, 4, 5]
# Traverse directly without creating a new container
for number in numbers:
print(number)
If a new list is created:
numbers = [1, 2, 3, 4, 5]
copied = numbers.copy()
The second approach requires creating an additional container and storing references to the elements in the original list.
For a list containing n elements, the copy operation usually requires O(n) extra space.
3. Notes on Big O Notation
Big O mainly describes an upper bound on growth and does not directly represent actual running time.
For example:
- O(n) is not necessarily slower than O(n\log n) at all data scales.
- The constant overhead of different algorithms may differ.
- The Python interpreter, hardware, and memory access patterns affect actual time consumption.
- The complexity of some container operations needs to be distinguished between average case, worst case, and amortized complexity.
When analyzing container performance, you cannot just memorize a complexity number; you also need to understand the conditions under which it holds.
3. The Underlying Data Structures of Python Containers
Before understanding performance, first understand the data structures behind common containers.
| Container | Typical underlying structure | Main characteristics |
|---|---|---|
list |
Dynamic array | Fast index access, efficient appends at the end |
tuple |
Fixed-length sequence storage | Immutable, suitable for fixed data |
dict |
Hash-table-related structure | Efficient key lookup on average |
set |
Hash-table-related structure | Efficient membership testing on average |
frozenset |
Hash-table-related structure | Immutable set |
str |
Immutable string storage | Suitable for text processing |
deque |
Double-ended queue structure | Efficient insertion and deletion at both ends |
heapq |
Heap structure built on a list | Efficient retrieval of the smallest element |
Note that the descriptions above reflect common Python implementations, especially the typical implementation in CPython. The Python language specification does not require all interpreters to use exactly the same internal structures.
4. Time complexity of list
Lists are one of the most commonly used containers in Python.
In CPython, lists are typically implemented as dynamic arrays.
A dynamic array allocates a contiguous block of pointer storage used to hold object references.
1. Complexity of common list operations
| Operation | Time complexity | Notes |
|---|---|---|
list[i] |
O(1) | Access by index |
list[i] = x |
O(1) | Modify the reference at a given position |
append(x) |
Amortized O(1) | Append at the end |
pop() |
O(1) | Remove the last element |
insert(0, x) |
O(n) | Insert at the beginning |
pop(0) |
O(n) | Remove the first element |
remove(x) |
O(n) | Find and remove the first matching element |
index(x) |
O(n) | Find the position of an element |
count(x) |
O(n) | Count occurrences of an element |
x in list |
O(n) | Linear membership test |
len(list) |
O(1) | Get the number of elements |
list.copy() |
O(n) | Shallow copy |
list[a:b] |
O(k) | Create a slice containing k elements |
reverse() |
O(n) | In-place reversal |
sort() |
O(n\log n) | Typical worst-case complexity |
sorted(list) |
O(n\log n) | Sort and create a new list |
Among these, the amortized complexity of append() is worth understanding in particular.
2. Why append is amortized O(1)
Dynamic arrays have a notion of capacity.
When a list appends an element:
- If the current capacity is sufficient, write the new element directly.
- If the capacity is insufficient, allocate larger storage.
- Migrate the existing element references to the new space.
- Then add the new element.
Resizing may require O(n) work, but resizing does not happen on every append.
Therefore, when performing a large number of append() operations consecutively, the average cost per operation is constant, i.e., amortized O(1).
Example:
numbers = []
for i in range(100000):
numbers.append(i)
Although an individual append may trigger resizing, the overall append process usually has good performance.
3. Why insertion at the beginning of a list is O(n)
numbers = [10, 20, 30, 40]
numbers.insert(0, 5)
When inserting an element at the beginning of a list, the existing elements must shift to make room for the new element.
If the list has n elements, nearly n element references may need to be moved.
Therefore:
Removing the first element likewise requires shifting the subsequent elements.
numbers = [10, 20, 30, 40]
numbers.pop(0)
If you frequently insert or delete at both ends, a regular list is not recommended.
4. Complexity of list sorting
Python’s list.sort() and sorted() use the Timsort sorting algorithm.
Typical complexity:
- Best case: O(n), for data that is already sorted or has long sorted runs.
- Average case: O(n\log n).
- Worst case: O(n\log n).
Example:
scores = [90, 70, 85, 95, 60]
scores.sort()
print(scores)
# [60, 70, 85, 90, 95]
sort() modifies the list in place and does not create a full copy of the sorted result.
scores = [90, 70, 85]
result = sorted(scores)
print(scores)
# [90, 70, 85]
print(result)
# [70, 85, 90]
sorted() returns a new list, so you also need to account for the extra space of the result list.
5. Suggestions for optimizing list performance
- Use
append()to add at the end whenever possible. - Avoid frequently calling
insert(0, x)on large lists. - When checking membership frequently, consider using a set.
- Do not repeatedly perform costly list searches in a loop.
- When sorting existing data, prefer the built-in sorting methods.
- If you only need to iterate, do not copy the list unnecessarily.
V. Time Complexity of Tuples (tuple)
A tuple is an immutable sequence.
Like a list, it supports indexed access and iteration, but its element references cannot be modified after creation.
1. Complexity of Common Tuple Operations
| Operation | Time Complexity | Description |
|---|---|---|
tuple[i] |
O(1) | Indexed access |
tuple[i:j] |
O(k) | Create a slice |
x in tuple |
O(n) | Linear search |
tuple.index(x) |
O(n) | Find an element's position |
tuple.count(x) |
O(n) | Count occurrences of an element |
len(tuple) |
O(1) | Get the length |
tuple + other |
O(n+m) | Create a concatenated result |
tuple * k |
O(nk) | Create a repeated result |
| Iteration | O(n) | Access each element one by one |
2. Why tuples cannot be modified directly
numbers = (10, 20, 30)
# TypeError
numbers[0] = 100
Tuple immutability means that the references to the elements it holds cannot be modified.
However, if a tuple contains mutable objects, the inner objects can still be modified:
data = ([1, 2], [3, 4])
data[0].append(100)
print(data)
# ([1, 2, 100], [3, 4])
Therefore, a tuple's immutability does not mean its inner objects are necessarily immutable.
3. Performance characteristics of tuples
Tuples are suitable for:
- Data with a fixed structure.
- Records that do not need to be modified.
- Functions returning multiple values.
- Use as dictionary keys that satisfy the hashing requirements.
- Storing fixed configurations and coordinates.
Both tuples and lists have an indexed access complexity of O(1), so you cannot simply assume that tuples are faster than lists in every operation.
Actual performance also depends on the data size, the type of operation, and the specific implementation.
6. Time Complexity of Dictionaries (dict)
A dictionary is one of the most important mapping containers in Python.
It accesses values (Value) through keys (Key), and common implementations are based on hash tables.
1. Complexity of common dictionary operations
| Operation | Average time complexity | Worst case |
|---|---|---|
dict[key] |
O(1) | O(n) |
dict[key] = value |
O(1) | O(n) |
key in dict |
O(1) | O(n) |
get(key) |
O(1) | O(n) |
pop(key) |
O(1) | O(n) |
del dict[key] |
O(1) | O(n) |
len(dict) |
O(1) | O(1) |
dict.copy() |
O(n) | O(n) |
keys() |
O(1) | O(1) |
values() |
O(1) | O(1) |
items() |
O(1) | O(1) |
| Iterate over dictionary | O(n) | O(n) |
Here, keys(), values(), and items() create view objects and do not immediately copy all elements in the entire dictionary.
Only when actually iterating over a view do the elements need to be processed one by one.
2. Why dictionary lookup is O(1) on average
The basic process of dictionary lookup can be understood as:
- Compute the hash value of the key.
- Locate candidate storage positions based on the hash value.
- Check whether the candidate key matches.
- Return the corresponding value.
Ideally, the target key can be located quickly without traversing the entire dictionary.
However, different keys may produce the same hash value; this situation is called a hash collision (Hash Collision).
The dictionary needs to handle collisions further, so an average of O(1) does not mean that only one operation is performed in all cases.
3. Why dictionary worst case can be O(n)
If many keys have hash collisions, lookup may need to check multiple candidate positions.
In extreme cases, lookup cost can degrade to linear level.
Therefore, the O(1) for dictionaries is a description of average-case complexity, not an unconditional guarantee.
4. Why dictionary views have low creation cost
user = {
"name": "Alice",
"age": 25,
"city": "Tokyo"
}
keys = user.keys()
values = user.values()
items = user.items()
These operations create view objects rather than copying all keys and values.
user["country"] = "Japan"
print(list(keys))
# ['name', 'age', 'city', 'country']
Views reflect subsequent changes to the dictionary.
But if you need an independent list, you must explicitly convert it:
keys_list = list(user.keys())
This requires O(n) time and extra space.
5. Dictionary Performance Optimization Tips
- Use a dictionary to store data that needs fast lookup by key.
- Choose keys with stable hashing and a good hash distribution where possible.
- Avoid using custom objects whose mutable state participates in hashing as keys.
- Do not repeatedly recompute the same expensive key values inside a loop.
- For scenarios that only require iteration, use
for key in dataordata.items()directly. - For operations that merge many key-value pairs, evaluate the merge approach and the data scale.
VII. Time Complexity of Sets: set and frozenset
Sets are usually implemented with hash tables; their main characteristics are unique elements and efficient membership testing.
1. Complexity of Common Set Operations
| Operation | Average Time Complexity | Worst Case |
|---|---|---|
x in set |
O(1) | O(n) |
add(x) |
O(1) | O(n) |
remove(x) |
O(1) | O(n) |
discard(x) |
O(1) | O(n) |
pop() |
O(1) | Depends on internal state |
len(set) |
O(1) | O(1) |
copy() |
O(n) | O(n) |
| Iteration | O(n) | O(n) |
2. Set Membership Testing
Both lists and sets can perform membership testing:
numbers = list(range(100000))
number_set = set(numbers)
print(99999 in numbers)
print(99999 in number_set)
The main differences between the two operations are:
- A list usually needs to compare elements one by one.
- A set usually locates candidate elements through hashing.
Therefore:
Here the set's O(1) is the average case.
3. Complexity of Set Operations
Sets also support union, intersection, difference, and symmetric difference.
| Operation | Typical Complexity | Notes |
|---|---|---|
Union A \| B |
(O( | A |
Intersection A & B |
Usually related to the smaller set and lookup cost | Find common elements |
Difference A - B |
Usually related to the left-hand set and lookup cost | Remove elements that exist in the right-hand set |
Symmetric difference A ^ B |
Usually related to the sizes of both sets | Keep elements that exist on only one side |
Subset test A <= B |
Usually related to the size of A and the cost of membership lookup | Check whether all elements are present |
These complexities depend on the average efficiency of hash operations, the sizes of the two sets, and the specific implementation; not all set operations can simply be treated as O(1).
4. Set Performance Optimization Tips
- Prefer sets for large numbers of membership tests.
- Use sets to eliminate duplicate elements.
- Do not rely on the insertion order of a set.
- Set elements must be hashable.
- Use
sorted()when you need sorted results. - Use
frozensetwhen you need an immutable set.
VIII. Time Complexity of Strings: str
Strings are immutable sequences, commonly used for text processing.
1. Complexity of Common String Operations
| Operation | Typical time complexity | Notes |
|---|---|---|
s[i] |
O(1) | Index access |
len(s) |
O(1) | Get the length |
x in s |
Upper bound of O(nm) for simple matching | Substring search; the specific algorithm may perform better |
s.find(x) |
Related to substring search | Find a substring |
s.count(x) |
Related to scanning and matching | Count occurrences of a substring |
s.lower() |
O(n) | Creates a converted result |
s.upper() |
O(n) | Creates a converted result |
s.replace(a, b) |
Usually on the order of O(n+m) | Creates a replacement result; the specifics depend on matching and the output length |
s.split() |
Usually O(n) | Split a string |
s.join(iterable) |
Depends on the total number of input characters and the output length | Join strings |
s + t |
Depends on the result length | Creates a new string |
2. Why string concatenation can cause performance problems
Strings are immutable objects.
Every time you concatenate with +, a new string result is created.
result = ""
for i in range(10000):
result += str(i)
Repeated concatenation inside a loop can cause a large amount of duplicated data copying.
If every concatenation has to copy the string content built up so far, the overall amount of work can reach quadratic scale.
Using join() is more recommended:
parts = []
for i in range(10000):
parts.append(str(i))
result = "".join(parts)
join() can construct the final result from the input content, and is usually more efficient than repeatedly using + inside a loop.
3. Using f-strings
name = "Alice"
age = 25
message = f"{name} is {age} years old."
f-strings are suitable for formatted output.
If you need to concatenate a large number of separate string fragments, you should still consider join() based on the actual situation.
9. Time complexity of the deque double-ended queue
collections.deque is a double-ended queue provided by Python.
It is suitable for scenarios where elements are frequently added to or removed from either end of the queue.
1. Complexity of common deque operations
| Operation | Time complexity | Description |
|---|---|---|
append(x) |
O(1) | Append on the right |
appendleft(x) |
O(1) | Append on the left |
pop() |
O(1) | Remove from the right |
popleft() |
O(1) | Remove from the left |
extend(iterable) |
O(k) | Batch append on the right |
extendleft(iterable) |
O(k) | Batch append on the left |
rotate(k) |
Depends on rotation distance | Rotate the deque |
d[i] |
Access at middle positions may be O(n) | Access at both ends is more efficient |
x in d |
O(n) | Membership lookup |
2. Why deque is suitable for queues
Using a list to simulate a queue:
queue = []
queue.append("task-1")
queue.append("task-2")
queue.append("task-3")
task = queue.pop(0)
pop(0) needs to shift subsequent elements, with a time complexity of O(n).
Using deque:
from collections import deque
queue = deque()
queue.append("task-1")
queue.append("task-2")
queue.append("task-3")
task = queue.popleft()
Insertion and deletion at both ends are usually O(1).
3. Typical applications of deque
- Message queues.
- Task scheduling.
- Breadth-first search.
- Sliding window.
- Recently accessed records.
- Data processing at both ends.
4. Choosing between deque and list
| Scenario | Recommended container |
|---|---|
| Frequent index-based reads | list |
| Frequent appends and deletions at the tail | list |
| Frequent insertions and deletions at the head | deque |
| Alternating operations at both ends | deque |
| Need sorting | list |
| Ordinary queue | deque |
10. Time Complexity of heapq Heap Operations
heapq is a heap operation module provided by the Python standard library.
It implements a min-heap (Min Heap) based on a list.
The characteristics of a heap are:
- The value of a parent node is not greater than that of its child nodes.
- The smallest element is at the top of the heap.
- The current smallest element can be obtained efficiently.
1. Complexity of Common Heap Operations
| Operation | Time complexity | Description |
|---|---|---|
heap[0] |
O(1) | View the smallest element |
heappush() |
O(\log n) | Insert an element |
heappop() |
O(\log n) | Pop the smallest element |
heapify() |
O(n) | Convert a list into a heap in place |
heapreplace() |
O(\log n) | Pop and then insert |
heappushpop() |
O(\log n) | Insert first, then pop, with an optimized implementation |
nlargest(k, data) |
Depends on n, k, and the implementation strategy | Get the largest k elements |
nsmallest(k, data) |
Depends on n, k, and the implementation strategy | Get the smallest k elements |
2. Basic Usage of a Heap
import heapq
numbers = [30, 10, 50, 20, 40]
heapq.heapify(numbers)
print(numbers[0])
# 10
heapq.heappush(numbers, 5)
smallest = heapq.heappop(numbers)
print(smallest)
# 5
3. What Scenarios Suit a Heap
- Priority queues.
- Top K problems.
- Scheduled task dispatching.
- Priority queues in shortest-path algorithms.
- Multiway merging.
- Retrieving the smallest or largest candidate value in real time.
If you only need to keep retrieving the smallest element, a heap is usually a better fit than sorting the entire list every time.
XI. Summary Table of Common Container Operation Complexities
The core performance characteristics of common containers are summarized below.
| Operation | list | tuple | dict | set | deque |
|---|---|---|---|---|---|
| Index access | O(1) | O(1) | N/A | N/A | May be O(n) at middle positions |
| Membership test | O(n) | O(n) | O(1) average | O(1) average | O(n) |
| Append at tail | O(1) amortized | Not supported | N/A | N/A | O(1) |
| Prepend at head | O(n) | Not supported | N/A | N/A | O(1) |
| Remove from tail | O(1) | Not supported | N/A | N/A | O(1) |
| Remove from head | O(n) | Not supported | N/A | N/A | O(1) |
| Get length | O(1) | O(1) | O(1) | O(1) | O(1) |
| Iteration | O(n) | O(n) | O(n) | O(n) | O(n) |
Notes:
- O(1) in the table indicates the typical complexity.
- Membership tests on dictionaries and sets are usually O(1) on average, but may be O(n) in the worst case.
- Tuples do not support in-place appending or removal, but you can create a new tuple by concatenation.
- Index access in the middle of a deque is less efficient than for a list.
- Different Python implementations may differ in their internal implementations.
12. How to Choose the Right Python Container
When choosing a container, decide based on the most frequent operations, not just on what the data looks like.
1. Choose Based on Operation Type
| Main requirement | Recommended container | Reason |
|---|---|---|
| Read data by position | list |
Index access O(1) |
| Store fixed-structure data | tuple |
Immutable sequence |
| Look up data by key | dict |
Average lookup O(1) |
| Quickly check whether an element exists | set |
Average membership test O(1) |
| Deduplication | set |
Elements are unique |
| Frequent insertions/deletions at both ends | deque |
Operations at both ends O(1) |
| Continuously get the minimum element | heapq |
Access to heap top O(1) |
| Process text | str |
Dedicated string operations |
| Store an immutable set | frozenset |
Immutable and hashable when conditions are met |
2. Container Selection Decision Flow
flowchart TD
A["Choose a Python container"] --> B{"What is the main operation?"}
B -->|"Access by position"| C["list or tuple"]
B -->|"Lookup by key"| D["dict"]
B -->|"Membership test or deduplication"| E["set or frozenset"]
B -->|"Insert/delete at both ends"| F["deque"]
B -->|"Continuously get minimum"| G["heapq"]
B -->|"Text processing"| H["str"]
C --> I{"Does the data need to be modified?"}
I -->|Yes| J["Choose list"]
I -->|No| K["Consider tuple"]
E --> L{"Does the set need to be modified?"}
L -->|Yes| M["Choose set"]
L -->|No| N["Choose frozenset"]
J --> O["Evaluate data size and operation frequency"]
K --> O
D --> O
M --> O
N --> O
F --> O
G --> O
H --> O
O --> P["Choose and verify performance"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style I fill:#FFF5DE,stroke:#E8D29A,color:#334155
style J fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style K fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style L fill:#FFF5DE,stroke:#E8D29A,color:#334155
style M fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style N fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style O fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style P fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px