Skip to content

Arrays and Python lists

A Python list gives each element an integer index. In CPython, the list stores a contiguous array of references to objects. The objects themselves can live elsewhere in memory. The list grows when necessary, so interview questions usually use it as a dynamic array.

Read complexity and interview method before comparing the operation costs below. The examples use invented integer inputs.

An index identifies a position, not a value. For a list of length n, the first index is 0 and the last is n - 1. Negative indices count from the end, so values[-1] selects the last element.

Operation Time Reason
values[i] or values[i] = x O(1) The index selects one reference.
values.append(x) O(1) amortized Most appends use spare capacity; an occasional resize copies references.
values.pop() O(1) amortized Removal occurs at the end; an occasional shrink can resize storage.
values.insert(0, x) or values.pop(0) O(n) The remaining references must move.
x in values O(n) A scan may inspect every element.
values[a:b] O(k) A new list receives the k selected references.

These costs assume constant-time element comparisons and ordinary CPython list behavior. An individual append can take O(n) time when the backing array grows. Amortized O(1) describes the total cost across a sequence of appends.

values = [7, 2, 5]
print("Initial:", values)
values.append(9)
print("Append 9:", values)
values.insert(1, 4)
print("Insert 4 at index 1:", values)
removed = values.pop(0)
print("Remove index 0:", removed, values)
print("Index 2:", values[2])
Initial: [7, 2, 5]
Append 9: [7, 2, 5, 9]
Insert 4 at index 1: [7, 4, 2, 5, 9]
Remove index 0: 7 [4, 2, 5, 9]
Index 2: 5

Assignment gives another name to the same list. A slice copies the outer list, but it does not copy nested objects. Use this distinction when an interviewer asks whether your solution changes its input.

original = [7, 2, 5]
alias = original
copied = original[:]
alias[0] = 8
print("Original after alias assignment:", original)
print("Separate outer copy:", copied)
nested = [[7], [2]]
shallow = nested[:]
shallow[0].append(9)
print("Nested original:", nested)
print("Nested shallow copy:", shallow)
Original after alias assignment: [8, 2, 5]
Separate outer copy: [7, 2, 5]
Nested original: [[7, 9], [2]]
Nested shallow copy: [[7, 9], [2]]

Suppose a sensor buffer uses zero for a discarded observation. Move every nonzero value to the front of the same list, preserving its order. Return the length of that retained prefix. The caller ignores every position after that prefix.

A second list solves the problem with O(n) additional space. Instead, keep a read position and a write position. Before each iteration, values[:write] contains exactly the retained values from the positions already read. The write position never passes the read position, so a write cannot erase an unread value.

def compact_nonzero(values: list[int]) -> int:
"""Move nonzero values into an ordered prefix of the same list.
Args:
values: Integer values to modify in place.
Returns:
The number of retained values. The remaining suffix is unspecified.
"""
write = 0
for read in range(len(values)):
if values[read] != 0:
values[write] = values[read]
write += 1
return write
buffer = [0, 7, 0, 2, 5]
write = 0
print("read value write retained")
for read in range(len(buffer)):
current = buffer[read]
if current != 0:
buffer[write] = current
write += 1
print(read, current, write, buffer[:write])
sample = [0, 7, 0, 2, 5]
kept = compact_nonzero(sample)
print("Retained prefix:", sample[:kept])
print("Full buffer:", sample)
read value write retained
0 0 0 []
1 7 1 [7]
2 0 1 [7]
3 2 2 [7, 2]
4 5 3 [7, 2, 5]
Retained prefix: [7, 2, 5]
Full buffer: [7, 2, 5, 2, 5]

The full buffer still contains values in the unused suffix. Do not return the full list as the filtered answer. Use the returned length to identify the answer, or explicitly copy the retained prefix if the interface requires a new list.

The algorithm examines each of n positions once, so its time is O(n). It uses two indices and no additional collection, so its auxiliary space is O(1). The displayed trace copies prefixes for explanation; that trace can take O(n²) total time and is separate from the function. The final sample[:kept] display also allocates a copy of the answer.

for case in ([], [0], [6], [0, 0], [3, -2, 0, 3]):
working = case[:]
length = compact_nonzero(working)
expected = [value for value in case if value != 0]
assert working[:length] == expected
assert len(working) == len(case)
print("Boundary checks passed.")
Boundary checks passed.
  • Solve Remove Element with a read position and a write position. State which prefix belongs to the answer.
  • Solve Move Zeroes after this lesson. Its required suffix differs from this example, so fill the remaining positions explicitly.

Continue with hash maps when a scan needs information about earlier values.

Download the Python source to run the complete example locally.

The Python design FAQ explains the array representation of a CPython list. It connects indexed access to the underlying references.

The Python data structures tutorial describes list methods and their mutation behavior. Compare its operation definitions with the table above.

Python’s copy documentation distinguishes shallow and deep copies. It explains why the nested example shares its inner lists.