Python Arrays: Operations, Patterns, and Placement Tips (2026)
Learn Python arrays with the array module, lists vs arrays, common operations, time complexity, and classic placement patterns like rotation and two-sum.
Python’s array module gives you a typed, compact alternative to the built-in list. Understanding when to use each one is a genuine differentiator in placement coding rounds.
What Python’s array Module Actually Does
A Python list is flexible: it can hold integers, strings, floats, and objects in any combination. That flexibility costs memory. Each element in a list is a full Python object reference, which adds overhead.
array.array trades flexibility for compactness. Every element must share the same C-level type, declared up front with a type code. The Python 3 array module documentation defines the full set; the codes you’ll use in placement contexts are:
| Type code | C type | Python type | Typical size |
|---|---|---|---|
'b' | signed char | int | 1 byte |
'B' | unsigned char | int | 1 byte |
'i' | signed int | int | 2 bytes |
'I' | unsigned int | int | 2 bytes |
'l' | signed long | int | 4 bytes |
'f' | float | float | 4 bytes |
'd' | double | float | 8 bytes |
One important note for Python 3.13 users: the 'u' (Unicode char) type code was deprecated in 3.3 and removed in 3.13. Legacy tutorials that use array('u', ...) will raise a ValueError on current Python. Don’t copy them.
What about numpy? NumPy arrays (numpy.ndarray) are the standard for numerical computing: they support multi-dimensional shapes, vectorised operations, and a far richer type system. For placement online judges, numpy is usually not available. The array module is always available in the standard library; Python lists always are. Know all three; default to lists unless memory efficiency is the stated constraint.
Creating, Indexing, and Slicing Arrays
Import the class directly:
from array import array
# Signed integers
arr = array('i', [10, 20, 30, 40, 50])
# Floats
arr_f = array('f', [1.1, 2.2, 3.3])
Indexing works identically to lists, zero-based:
from array import array
arr = array('i', [10, 20, 30, 40, 50])
print(arr[0]) # 10
print(arr[-1]) # 50
print(arr[2]) # 30
Negative indices count from the end: arr[-1] is the last element, arr[-2] the second-to-last.
Slicing returns a new array.array of the same type code:
from array import array
arr = array('i', [10, 20, 30, 40, 50])
print(arr[1:4]) # array('i', [20, 30, 40])
print(arr[::-1]) # array('i', [50, 40, 30, 20, 10])
print(arr[::2]) # array('i', [10, 30, 50])
Modifying a single element is a direct assignment:
from array import array
arr = array('f', [1.1, 2.2, 3.3])
arr[2] = 4.4
print(arr[0], arr[1], arr[2]) # 1.1 2.2 4.4
Common Operations with Worked Examples
Appending and extending
append() adds one element; extend() adds all elements from any iterable.
from array import array
arr = array('i', [10, 20, 30])
arr.append(40)
print(arr) # array('i', [10, 20, 30, 40])
arr.extend([50, 60])
print(arr) # array('i', [10, 20, 30, 40, 50, 60])
Inserting at a position
insert(i, x) inserts value x before index i. Everything from index i onward shifts right (O(n) time).
from array import array
arr = array('i', [10, 20, 30])
arr.insert(1, 15)
print(arr) # array('i', [10, 15, 20, 30])
Removing elements
pop(i) removes and returns the element at index i. Default index is -1 (the last element).
from array import array
arr = array('i', [10, 20, 30])
val = arr.pop(0)
print(val) # 10
print(arr) # array('i', [20, 30])
remove(x) deletes the first occurrence of value x. Raises ValueError if x is not present.
from array import array
arr = array('i', [10, 20, 30, 20])
arr.remove(20)
print(arr) # array('i', [10, 30, 20])
Reversing and sorting
reverse() modifies the array in place:
from array import array
arr = array('i', [10, 20, 30])
arr.reverse()
print(arr) # array('i', [30, 20, 10])
array.array has no built-in .sort() method. Convert to a list, sort, then convert back; or sort a list directly:
from array import array
arr = array('i', [30, 10, 20])
lst = list(arr)
lst.sort()
arr = array('i', lst)
print(arr) # array('i', [10, 20, 30])
For sorting strings or characters, see sorting strings in Python.
Counting occurrences and finding the index
from array import array
arr = array('i', [10, 20, 10, 30, 10])
print(arr.count(10)) # 3
print(arr.index(30)) # 3 (first position where 30 appears)
index(x) raises ValueError if x is absent; guard with a check or a try-except in production code.
Length
len(arr) returns the number of elements, O(1):
from array import array
arr = array('i', [10, 20, 30, 40, 50])
print(len(arr)) # 5
For computing the sum of all elements, see sum of array elements in Python.
Iterating
All three iteration styles work identically on array.array and on lists:
from array import array
arr = array('i', [10, 20, 30])
# Style 1: direct iteration
for x in arr:
print(x, end=' ') # 10 20 30
# Style 2: index-based
for i in range(len(arr)):
print(arr[i], end=' ') # 10 20 30
# Style 3: enumerate (preferred when you need both index and value)
for i, x in enumerate(arr):
print(f"arr[{i}] = {x}")
# arr[0] = 10
# arr[1] = 20
# arr[2] = 30
Time Complexity of Array Operations
These figures apply to both array.array and Python lists unless noted. The Python wiki time-complexity reference covers the list in detail; array.array behaves the same for all structural operations.
| Operation | Time complexity | Notes |
|---|---|---|
Index access arr[i] | O(1) | Direct memory offset |
Append arr.append(x) | O(1) amortised | Occasional resize doubles capacity |
Extend arr.extend(iterable) | O(k) | k = length of iterable |
Insert at front arr.insert(0, x) | O(n) | Shifts all elements right |
Insert at middle arr.insert(i, x) | O(n) | Shifts elements from i onward |
Pop from end arr.pop() | O(1) | No shifting needed |
Pop from front arr.pop(0) | O(n) | Shifts all elements left |
Remove by value arr.remove(x) | O(n) | Linear scan then shift |
Search x in arr | O(n) | Linear scan |
Length len(arr) | O(1) | Cached internally |
Reverse arr.reverse() | O(n) | In-place |
| Iteration | O(n) | Full traversal |
The practical lesson for placement rounds: prefer operations that touch only the end of the array (append, pop()). Front-of-array inserts and removals are expensive on large inputs. Examiners sometimes specifically craft test cases to expose this.
When to Use list vs array vs numpy
The choice matters less often than tutorials suggest, but there is a clean rule:
| Scenario | Best choice | Reason |
|---|---|---|
| Mixed types in one collection | list | array.array rejects mixed types |
| Large homogeneous integers or floats, memory constrained | array.array | Less memory per element vs list |
| Numerical computing, matrix operations, vectorised math | numpy.ndarray | Built-in vectorisation, much faster at scale |
| Placement online judge (no numpy) | list | Always available, cleaner syntax, adequate speed |
| Need sorting, standard library algorithms | list | Built-in sort(), sorted(), heapq work on lists natively |
One more note: for finding the greatest of three numbers in Python and similar simple comparisons, a plain list is the right container. array.array adds import overhead with no benefit at that scale.
Classic Placement Patterns
These four patterns appear repeatedly in campus coding rounds. The intent here is to name each pattern and give you the shape of the solution; for deeper worked examples and a Python basics practice set, follow the sibling links.
Array rotation
Rotate an array of n elements left by k positions.
def rotate_left(arr, k):
n = len(arr)
k = k % n # handle k >= n
return arr[k:] + arr[:k]
# Example
lst = [1, 2, 3, 4, 5]
print(rotate_left(lst, 2)) # [3, 4, 5, 1, 2]
This runs in O(n) time and O(n) space. An in-place O(1) space version reverses three subarrays.
Maximum subarray sum (Kadane’s algorithm)
Find the contiguous subarray with the largest sum.
def max_subarray(arr):
best = arr[0]
current = arr[0]
for x in arr[1:]:
current = max(x, current + x)
best = max(best, current)
return best
# Example
lst = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
print(max_subarray(lst)) # 6 (subarray [4, -1, 2, 1])
Time O(n), space O(1). Frequent in mid-level placement rounds.
Two-sum
Given an unsorted array and a target, find two indices whose elements sum to the target.
def two_sum(arr, target):
seen = {}
for i, x in enumerate(arr):
complement = target - x
if complement in seen:
return (seen[complement], i)
seen[x] = i
return None
# Example
lst = [2, 7, 11, 15]
print(two_sum(lst, 9)) # (0, 1)
Time O(n), space O(n) using a hash map. The naive nested-loop version is O(n²): fine for small inputs, but fails on large arrays with tight time limits.
Frequency count
Count how many times each element appears. Common as a preprocessing step.
def frequency_count(arr):
freq = {}
for x in arr:
freq[x] = freq.get(x, 0) + 1
return freq
# Example
lst = [1, 2, 2, 3, 3, 3]
print(frequency_count(lst)) # {1: 1, 2: 2, 3: 3}
Time O(n), space O(k) where k is the number of distinct values.
Understanding how these patterns connect to the time-complexity table above is what separates rote memorisation from confident problem-solving. If you want to go further: TinkerLLM is a Python-first playground where you can experiment with these patterns on real datasets at ₹299, without needing a local environment set up.
FACE Prep’s cluster of Python practice articles covers the full range from basic programs to sorting and searching. The sibling links above are the fastest path to filling gaps before a campus drive.
Primary sources
Frequently asked questions
What is the difference between a Python list and an array?
A list holds elements of any type. array.array enforces a single type code (e.g., 'i' for signed int), so it uses less memory for large homogeneous numeric sequences.
How do I create an integer array in Python?
Import array and call array('i', [1, 2, 3]). The first argument is the type code; 'i' means signed int. The second argument is any iterable of initial values.
What does array.append() do and how fast is it?
It adds one element to the end of the array. Time complexity is O(1) amortised, same as list.append(). For multiple elements at once, use extend().
Is Python array.array faster than a list?
For raw numeric storage, array.array uses less memory than a list. But CPython's list is often faster for mixed in-place operations because of its optimised internals. For heavy numerical work, numpy arrays are the right choice.
How do you reverse an array in Python?
Call arr.reverse() to reverse in place. Or use arr[::-1] for a reversed copy, but note that slicing an array.array returns a list, not another array.array.
What type codes does array.array support in Python 3.13?
Common ones: 'b' (signed byte), 'B' (unsigned byte), 'i' (signed int), 'I' (unsigned int), 'f' (float), 'd' (double). The 'u' Unicode type was removed in Python 3.13.
Can I use numpy arrays instead of array.array in placement coding rounds?
Numpy is rarely available on online judges used at campus drives. Default to Python lists or array.array; use numpy only when the problem explicitly allows it or asks for matrix operations.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)