✅ Arrays in Python – Master Note with Explanations & Examples
🔢 Array Basics and Creation
✅ Importing and Creating a Typed Array
Python’s array module stores data more efficiently than lists using typecodes.
A typecode defines the type and size of elements (e.g., 'i' for integer, 'f' for float).
CopyEdit:
import array as arr
a = arr.array('i', [1, 2, 3]) # 'i' = signed int (2 or 4 bytes depending on system)
✳️ Why use this? Saves memory and improves performance for large numeric data.
✅ Indexing (positive & negative)
Array indexing is zero-based (starts from 0).
Negative indexing accesses elements from the end of the array.
CopyEdit:
print(a[0]) # First element
print(a[-1]) # Last element
🔧 Array Manipulation
✅ Insert an Element at a Specific Index
insert(index, value) adds a value at a specified index, shifting others right.
CopyEdit:
a.insert(1, 10) # Inserts 10 at index 1
✅ Append an Element at the End
Adds value at the end of the array.
CopyEdit:
a.append(20)
✅ Update an Element
Access the index and assign a new value.
CopyEdit:
a[2] = 30 # Updates index 2 to 30
✅ Delete an Element using pop()
Removes and returns the element at a given index.
CopyEdit:
a.pop(1) # Removes element at index 1
✳️ Also useful: a.remove(value) removes the first occurrence of a value, not by index.
🧠 Advanced Array Operations
✅ Slicing with Steps
Syntax: array[start:stop:step]
Allows flexible element selection.
CopyEdit:
sliced = a[1:4:1] # Gets elements from index 1 to 3
✅ Reverse the Array
Use negative step in slicing to reverse.
CopyEdit:
reversed_a = a[::-1]
✳️ Trick: No need for a separate reverse() method in array module.
✅ Find Index of an Element
index(value) returns the first index where value appears.
CopyEdit:
idx = a.index(30)
✳️ Raises an error if the value is not found.
✅ Sort the Array
Built-in arrays don’t have a sort() method — use sorted() and wrap back in array.
CopyEdit:
sorted_list = sorted(a) # Returns a list
a = arr.array('i', sorted_list) # Convert back to array
✳️ For descending order: sorted(a, reverse=True)
📊 NumPy Arrays – For Advanced Use Cases
✅ Create a NumPy Array
NumPy arrays support vectorized operations, matrices, and faster math.
CopyEdit:
import numpy as np
na = np.array([1, 2, 3])
✅ Check Dimensions
.ndim gives the number of dimensions (1D, 2D, 3D...)
CopyEdit:
na1 = np.array([1, 2, 3])
print(na1.ndim) # 1
na2 = np.array([[1, 2], [3, 4]])
print(na2.ndim) # 2
✳️ Used in ML/AI for handling data like vectors, matrices, tensors.
✅ Create Arrays with Specific Shape
Use zeros(), ones(), or reshape() for structured arrays.
CopyEdit:
zeros_array = np.zeros((2, 3)) # 2 rows, 3 columns filled with 0
print(zeros_array)
✳️ This is helpful when initializing data for models or matrix operations.
✅ Vectorized Operations
NumPy supports operations on entire arrays at once.
CopyEdit:
na = np.array([1, 2, 3])
print(na + 5) # Output: [6 7 8]
✳️ Unlike Python lists, you don’t need to loop — NumPy does it faster and internally.
📝 Final Notes
✅ Use array.array for lightweight, typed, single-dimensional numeric data.
✅ Use NumPy for advanced data manipulation, multi-dimensional arrays, and
performance-heavy tasks.
❗ Python lists are flexible but slower and memory-heavy for numeric data processing.