Q&A
Array operations in Python
Overview
"Array" in Python usually means a list ([]), which can hold mixed types and grows/shrinks dynamically. When people say "array operations," they typically mean manipulating lists. Two specialized alternatives exist: the standard-library array.array (compact, single-type) and numpy.ndarray (vectorized math, the foundation of data science).
graph TD
A[Python 'array' options] --> B[list: dynamic, mixed-type, built-in]
A --> C[array.array: compact, single primitive type]
A --> D[numpy.ndarray: fast vectorized math]
B --> B1[Most common, general purpose]
D --> D1[Data science, ML, numeric computing]
style A fill:#1e1b4b,color:#fff
Core List Operations
Creating and accessing
nums = [10, 20, 30, 40, 50]
nums[0] # 10 (first)
nums[-1] # 50 (last, negative index from end)
len(nums) # 5
Slicing - list[start:stop:step]
nums[1:3] # [20, 30] (stop is exclusive)
nums[:2] # [10, 20]
nums[::2] # [10, 30, 50] (every 2nd)
nums[::-1] # [50, 40, 30, 20, 10] (reversed)
Adding elements
nums.append(60) # add to end -> [..., 50, 60]
nums.insert(0, 5) # insert at index 0
nums.extend([70, 80]) # add multiple
nums = nums + [90] # concatenation (creates a new list)
Removing elements
nums.pop() # remove & return last
nums.pop(0) # remove & return index 0
nums.remove(30) # remove first occurrence of value 30
del nums[1] # delete by index
nums.clear() # empty the list
Searching and membership
30 in nums # True / False
nums.index(30) # position of first 30 (ValueError if absent)
nums.count(20) # how many times 20 appears
Sorting and reversing
nums.sort() # in place, ascending
nums.sort(reverse=True) # descending
ordered = sorted(nums) # returns a NEW sorted list
nums.reverse() # in place
Iteration
for n in nums:
print(n)
for i, n in enumerate(nums): # index + value
print(i, n)
List Comprehensions (Pythonic transformation)
A concise way to build a new list by transforming/filtering:
squares = [x * x for x in range(5)] # [0, 1, 4, 9, 16]
evens = [x for x in nums if x % 2 == 0] # filter
The array Module (compact, typed)
When you need a memory-efficient array of a single primitive type:
import array
a = array.array('i', [1, 2, 3]) # 'i' = signed int
a.append(4)
a[0] # 1
It supports list-like operations but enforces one type code, saving memory for large numeric data.
NumPy Arrays (vectorized, high-performance)
For real numeric/scientific work, NumPy is the standard. Its key advantage is vectorization - operations apply to whole arrays without explicit loops, running in fast compiled code.
import numpy as np
arr = np.array([1, 2, 3, 4])
arr * 2 # array([2, 4, 6, 8]) -- elementwise, no loop
arr + arr # array([2, 4, 6, 8])
arr.sum() # 10
arr.mean() # 2.5
arr[arr > 2] # array([3, 4]) -- boolean masking
arr.reshape(2, 2) # 2x2 matrix
NumPy arrays are fixed-type, fixed-size (operations often return new arrays), and dramatically faster than lists for numeric workloads.
Choosing the Right One
| Need | Use |
|---|---|
| General-purpose, mixed types, simple code | list |
| Memory-efficient single-type numeric buffer | array.array |
| Fast math, matrices, data science / ML | numpy.ndarray |
Complexity Notes (list)
- Index access / append (amortized): O(1)
- Insert/remove at arbitrary position: O(n) (shifts elements)
- Search (
in,index): O(n) - Sort: O(n log n)
Why This Matters in Interviews
Know list slicing cold (it appears constantly), the difference between in-place (sort()) and new-object (sorted()) operations, list comprehensions, and why NumPy is faster (vectorization over compiled C, contiguous memory). Mentioning operation complexity (insert is O(n)) signals depth.
Common Pitfalls
- Confusing
sort()(mutates, returnsNone) withsorted()(returns new list). - Modifying a list while iterating over it.
- Expecting
list * 2to double values - it repeats the list ([1,2]*2 == [1,2,1,2]); use NumPy for elementwise math. - Shallow vs deep copy issues with nested lists (
copy.deepcopy).
References
- Python list docs: https://docs.python.org/3/tutorial/datastructures.html
- NumPy quickstart: https://numpy.org/doc/stable/user/quickstart.html