Sub topic 14
Python list, Java ArrayList and C++ vector
This chapter assumes you know the size/capacity split and the allocate-copy-replace resize from earlier chapters. All three standard containers below are dynamic arrays. They differ in growth policy, in what they store, and in the tools they give you to manage capacity.
Same idea, three vocabularies
| Aspect | Python `list` | Java `ArrayList` | C++ `std::vector` |
|---|---|---|---|
| Growth | About 1.125x plus a small constant (CPython) | 1.5x | 2x in GCC and Clang, 1.5x in MSVC |
| Initial capacity | 0 | 0, then 10 on the first add | 0 |
| Query capacity | Not exposed | Not exposed | `capacity()` |
| Reserve capacity | No direct call | `ensureCapacity(n)` | `reserve(n)` |
| Release spare room | Not exposed | `trimToSize()` | `shrink_to_fit()` |
| Stores | References to objects | References to objects | Values stored directly |
The C++ standard only requires that push_back be amortized O(1), so the factor is up to the implementation. Treat the numbers above as typical, not guaranteed.
Python list
A list keeps an array of pointers to objects. Its append, pop() and indexing run in O(1), and insert(0, x) and pop(0) shift every other pointer.
items = [10, 20, 30]
items.append(40)
items.insert(0, 5)
last = items.pop()
first = items.pop(0)
print(items, last, first)This prints [10, 20, 30] 40 5. The two middle-of-array calls, insert(0, 5) and pop(0), are the O(n) ones.
Python does not expose capacity, but you can watch it grow indirectly. sys.getsizeof reports the memory the list occupies, and it only changes when a resize happens.
import sys
data = []
last_size = sys.getsizeof(data)
for i in range(40):
data.append(i)
size = sys.getsizeof(data)
if size != last_size:
print(f"resize at length {len(data)}: {size} bytes")
last_size = sizeThe exact lengths and byte counts depend on the Python version and platform. What stays the same is that resizes are rare and get further apart.
Java ArrayList
ArrayList<E> holds an Object[]. When the array is full it allocates one about 1.5 times larger and copies the elements over. Because it stores references, ArrayList<Integer> holds boxed objects, not raw ints. That costs memory and hurts cache locality.
If you know the final size, tell the list once:
import java.util.ArrayList;
public class Demo {
public static void main(String[] args) {
ArrayList<Integer> nums = new ArrayList<>();
nums.ensureCapacity(1000);
for (int i = 0; i < 1000; i++) {
nums.add(i);
}
nums.trimToSize();
System.out.println(nums.size());
}
}C++ vector
std::vector<T> stores the elements themselves in one contiguous block. A vector<int> is therefore very compact and cache friendly. It is also the only one of the three where you can read capacity().
#include <iostream>
#include <vector>
int main() {
std::vector<int> v;
v.reserve(100);
for (int i = 0; i < 100; i++) {
v.push_back(i);
}
std::cout << v.size() << " " << v.capacity() << "\n";
}After reserve(100) no reallocation happens during the loop. The program prints 100 and then a capacity of at least 100.
What carries over
- A smaller growth factor wastes less memory but resizes more often.
- Pre-sizing removes repeated copying when you know the count.
- Inserting or removing near the front is O(n) in all three.
Exercise
You will add 1,000,000 integers to a C++ vector in a loop. What single call can you make beforehand to avoid every intermediate reallocation, and why is it safe for existing iterators to skip worrying about invalidation during the loop?
Show answer
Call v.reserve(1000000) before the loop. The capacity is then large enough for all pushes, so no reallocation occurs and no iterators, pointers or references are invalidated by growth.