How do you declare and append items to arrays and lists in Python? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you declare and append items to arrays and lists in Python?

message-square
0

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]]), whereas lst.extend([4, 5]) (or lst += [4, 5]) unpacks and appends each element individually ([1, 2, 3, 4, 5]).
  • .append() mutates in place and returns None:
    • Never write items = items.append("x")—that overwrites items with None. Call items.append("x") as a standalone statement.
  • 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, so grid[0][0] = 9 mutates every row ([[9, 0, 0], [9, 0, 0], [9, 0, 0]]). Always use a list comprehension: grid = [[0] * 3 for _ in range(3)].
  • Never use np.append() inside a Python loop for NumPy arrays:
    • Unlike list.append() (amortized $O(1)$), numpy.ndarray is fixed-size in memory—so np.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 Python list first (buf.append(val)) and convert once at the end with np.array(buf).
  • Prepending to the left (collections.deque vs. 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, use collections.deque (.append() / .appendleft() in $O(1)$).

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.