Use a built-in Python list (items = [] or items = [1, 2, 3]) with .append(x) (to add a single element in amortized $O(1)$ time) or .extend(iterable) (to append multiple items) for almost all general-purpose sequences, reserving array.array("i", ...) from the standard library array module or numpy.array(...) when you need compact, homogeneously typed numeric buffers.
Basic Example
import array
# 1. Recommended (general-purpose Python list — heterogeneous, dynamic):
fruits = ["apple", "banana"]
fruits.append("cherry") # Adds 1 item to the end (in-place)
fruits.extend(["date", "fig"]) # Appends each element from an iterable
print(fruits)
# Output: ['apple', 'banana', 'cherry', 'date', 'fig']
# 2. Standard library typed `array` (homogeneous C-backed primitives only):
# Typecodes: 'i' = signed int, 'f' = float, 'd' = double, 'B' = unsigned byte
nums = array.array("i", [10, 20])
nums.append(30) # Raises TypeError if you append a non-int like "abc"
nums.extend([40, 50])
print(nums)
# Output: array('i', [10, 20, 30, 40, 50])
Key Details & Edge Cases
.append(item)vs..extend(iterable)(the #1 nested-list bug):lst.append([4, 5])inserts the entire list[4, 5]as a single nested element ([1, 2, 3, [4, 5]]), whereaslst.extend([4, 5])(orlst +=) unpacks and appends each element individually ([1, 2, 3, 4, 5]).
.append()mutates in place and returnsNone:- Never write
items = items.append("x")—that overwritesitemswithNone. Callitems.append("x")as a standalone statement.
- Never write
- Avoid initializing 2D lists with
[[0] * 3] * 3(shared inner-list reference trap):- Multiplying a list of mutable lists (
grid = [[0] * 3] * 3) copies the same inner list reference 3 times, sogrid[0][0] = 9mutates every row ([[9, 0, 0], [9, 0, 0], [9, 0, 0]]). Always use a list comprehension:grid = [[0] * 3 for _ in range(3)].
- Multiplying a list of mutable lists (
- Never use
np.append()inside a Python loop for NumPy arrays:- Unlike
list.append()(amortized $O(1)$),numpy.ndarrayis fixed-size in memory—sonp.append(arr, val)allocates and copies the entire array on every single call ($O(n^2)$ total time for $n$ appends). Collect items in a standard Pythonlistfirst (buf.append(val)) and convert once at the end withnp.array(buf).
- Unlike
- Prepending to the left (
collections.dequevs.list.insert(0, x)):- Inserting at the front of a
list(lst.insert(0, x)) shifts every existing element right in $O(n)$ time. If you frequently append/pop at both ends, usecollections.deque(.append()/.appendleft()in $O(1)$).
- Inserting at the front of a
Comparison of Sequence / Array Types in Python
| Type | Declaration Syntax | Append Single / Multiple | Element Types | Best Used When |
|---|---|---|---|---|
list (Recommended) |
a = [] or a = [1, 2] |
a.append(x) / a.extend(it) (amortized $O(1)$) |
Any Python objects (mixed types allowed) | 95% of everyday Python collections, accumulators, and dynamic sequences. |
array.array (stdlib) |
a = array.array("d", [1.0]) |
a.append(x) / a.extend(it) (amortized $O(1)$) |
Single fixed C primitive type ("i", "d", "B") |
Memory-compact homogeneous numeric streams or binary buffer I/O without third-party deps. |
collections.deque |
d = deque([1, 2]) |
d.append(x) / d.appendleft(x) ($O(1)$ both ends) |
Any Python objects | FIFO queues, sliding windows, or fast prepending/appending at both ends. |
numpy.ndarray |
a = np.array([1, 2]) |
Avoid loop appends (accumulate in list, then np.array(lst)) |
Single fixed numeric/boolean dtype | Vectorized linear algebra, scientific computing, and large multi-dimensional matrices. |
You must log in or register to comment.
