Data Structures
Python array Module — Complete Beginner to Interview Guide
Learn Python's array module from scratch: what it is, every method explained one by one with output, and how it compares to list and numpy for interviews.
- Python
- Array
- DSA
- Data Structures
- Algorithm
1. What is the array Module?
Points to understand first:
- Python’s normal
listcan hold any mix of data types (numbers, text, other lists) at the same time. - A list does this by secretly storing pointers (memory addresses) to each object, not the raw values themselves.
- The
arraymodule gives you a different kind of array — one that stores only one fixed type of value, as raw bytes, just like arrays in C or Java. - Because of this, an
arrayuses less memory than alistholding the same numbers. - The trade-off: an
arraycan only hold one type of value — you cannot mix numbers and text in it. arrayis part of the Python standard library — no installation needed, justimport array.
2. Typecodes — Telling Python What Type to Store
Every array needs a typecode — a single letter that tells Python exactly what kind of value to store and how many bytes to use per item.
| typecode | C type | min bytes | python type |
|---|---|---|---|
| 'b' | signed char | 1 | int |
| 'B' | unsigned char | 1 | int |
| 'h' | signed short | 2 | int |
| 'H' | unsigned short | 2 | int |
| 'i' | signed int | 2 | int |
| 'I' | unsigned int | 2 | int |
| 'l' | signed long | 4 | int |
| 'L' | unsigned long | 4 | int |
| 'q' | signed long long | 8 | int |
| 'Q' | unsigned long long | 8 | int |
| 'f' | float | 4 | float |
| 'd' | double | 8 | float |
3. Creating an Array (Every Way)
3.1 From a List of Values
3.2 Empty Array
4. Accessing and Slicing — Works Just Like a List
Important beginner gotcha: you cannot assign a plain list into an array slice — the right-hand side must also be an array of the same typecode.
5. Every Array Method — Explained One by One
5.1 append(x) — Add One Item to the End
5.2 insert(index, x) — Insert at a Specific Position
5.3 extend(iterable) — Add Many Items at Once
5.4 remove(x) — Remove the First Matching Value
5.5 pop(index) — Remove and Return an Item
5.6 index(x) — Find the Position of a Value
5.7 count(x) — Count How Many Times a Value Appears
5.8 reverse() — Reverse In Place
5.9 tolist() — Convert to a Regular Python List
5.10 fromlist(list) — Add Items From a Regular List
5.11 tobytes() — Convert to Raw Bytes
When would you need this? When saving numbers to a file or sending them over a network in the most compact, raw binary form.
5.12 frombytes(bytes_obj) — Load From Raw Bytes
5.13 buffer_info() — Memory Address and Length
5.14 typecode and itemsize — Useful Attributes
6. All Methods in One Table (Quick Reference)
| method | what it does | time complexity |
|---|---|---|
| append(x) | Add x to the end | O(1) amortized |
| insert(i, x) | Insert x before index i | O(n) |
| extend(iterable) | Add each item of iterable to the end | O(k) |
| remove(x) | Remove first item equal to x | O(n) |
| pop(i=-1) | Remove & return item at index i | O(1) at end, O(n) elsewhere |
| index(x) | Find index of first x | O(n) |
| count(x) | Count occurrences of x | O(n) |
| reverse() | Reverse in place | O(n) |
| tolist() | Convert to a regular Python list | O(n) |
| fromlist(list) | Add items from a regular list | O(n) |
| tobytes() | Convert to raw bytes | O(n) |
| frombytes(b) | Load items from raw bytes | O(n) |
| buffer_info() | Memory address + length of the buffer | O(1) |
| typecode (attribute) | The single-letter type code, e.g. 'i' | O(1) |
| itemsize (attribute) | Bytes used per element | O(1) |
7. array vs list vs numpy.ndarray
| aspect | list | array.array | numpy.ndarray |
|---|---|---|---|
| Can mix data types? | Yes | No — one type only | No — one dtype only |
| Memory usage | Highest (stores pointers) | Lower (raw values) | Lower (raw values) |
| Math on the whole array at once? | No — needs a loop | No — needs a loop | Yes — vectorized, very fast |
| Needs installing? | Built-in | Built-in | pip install numpy |
| Best for | General everyday code | Compact single-type buffers, file/network I/O | Numeric & scientific computing |
Honest beginner advice:
- In most interview questions, you will use a normal
list— it’s the default, flexible choice. arrayis rarely required directly in interviews — but understanding it helps you understand memory and typed data.numpyis what you reach for when you need fast math on lots of numbers at once (covered in the next guide).
8. Interview Patterns (Question First, Then Solution)
8.1 Pattern: Running Totals (Prefix Sum on an Array)
❓ Interview Question:
- Problem: Given an
arrayof integers, return a newarraywhere each position holds the running total up to that point. - Example:
- Input:
array('i', [1, 2, 3, 4]) - Expected Output:
array('i', [1, 3, 6, 10])
- Input:
- Hint: Keep a running variable that adds up as you go, just like with a list.
✅ Approach:
- Create a new array of the same length, filled with zeros to start.
- Loop through the input, keeping a running sum.
- Store the running sum at each position of the new array.
Complexity: Time = O(n), Space = O(n) for the new result array.
8.2 Pattern: Find the Maximum Value Without Using max()
❓ Interview Question:
- Problem: Given an array of integers, find the largest value without using the built-in
max()function (interviewers often ask this to test your understanding of loops). - Example:
- Input:
array('i', [3, 7, 2, 9, 4]) - Expected Output:
9
- Input:
- Hint: Start by assuming the first item is the largest, then check every other item against it.
✅ Approach:
- Set
largest = values[0]as a starting guess. - Loop through the rest of the array.
- Any time you find a bigger value, update
largest.
Complexity: Time = O(n), Space = O(1).
9. Practice Problems (Try These Yourself)
- Write a function that reverses an
arraywithout using.reverse(). - Convert an
arrayof Celsius temperatures into anarrayof Fahrenheit temperatures. - Find the second-smallest value in an array.
- Merge two sorted arrays into one sorted array.
10. Key Takeaways
array.array(typecode, values)stores one fixed C-type of value — more memory-efficient than a list, but less flexible.- It shares most of a list’s methods (
append,pop,insert,remove,index,count,reverse, slicing). - Extra array-only methods handle binary conversion:
tobytes(),frombytes(),tolist(),fromlist(),buffer_info(). - Slice assignment requires another
arrayon the right side, not a plain list — a common beginner error. - In real interview settings,
listis still the default choice —arraymainly matters for compact, single-type numeric storage and binary I/O.