Arrays in Python: Complete Guide for DSA, Data Science, AI and Machine Learning
Introduction to Arrays
An array is a fundamental data structure used to store multiple elements in an organized sequence. Each element occupies a position that can be identified using an index.
Arrays are among the most important concepts in Data Structures and Algorithms (DSA). They are also used extensively in Data Science, scientific computing, Machine Learning and Artificial Intelligence.
list is commonly used to solve
array-based DSA problems. However, a Python list is not exactly
the same as a traditional fixed-size array. Python also provides
the array module and NumPy’s ndarray
for other array requirements.
Why are arrays important?
- Store and organize collections of data.
- Access elements directly using indexes.
- Implement searching and sorting algorithms.
- Solve common coding interview problems.
- Represent matrices, grids and numerical datasets.
- Store feature vectors and image data in Machine Learning.
arr = [10, 20, 30, 40, 50]
print(arr)
[10, 20, 30, 40, 50]
Understanding Array Fundamentals
What is an element?
An element is an individual value stored inside an array.
For example, in [10, 20, 30], the values 10, 20
and 30 are individual elements.
What is an index?
An index represents the position of an element. Python uses zero-based indexing, meaning the first element is at index 0.
Array structure
Each element has a corresponding index.
Characteristics of arrays
- Ordered: Elements maintain their sequence.
- Indexed: Elements can be accessed using positions.
- Mutable in Python lists: Elements can be updated.
- Dynamic size: Python lists can grow and shrink.
- Duplicates: Multiple elements can contain the same value.
- Mixed data types: Python lists can contain different types.
Types of arrays based on dimensions
One-dimensional array
A sequence of elements arranged in one dimension.
Two-dimensional array
Elements organized into rows and columns.
Multidimensional array
Data represented across three or more dimensions.
Arrays in Python
Python supports different ways to store array-like data. Choosing the right structure depends on the type of data and the operations you need to perform.
Python list
A list is the most commonly used structure for array-based DSA problems. It supports dynamic resizing and can store different data types.
arr = [10, 20, 30, 40, 50]
print(arr)
print(type(arr))
[10, 20, 30, 40, 50]
<class 'list'>
Python array module
Python’s built-in array module provides
typed arrays. All elements in an array must follow
the specified type code.
import array
arr = array.array('i', [10, 20, 30, 40])
print(arr)
print(arr[0])
array('i', [10, 20, 30, 40])
10
Here, 'i' represents a signed integer type
code. The available type codes depend on the Python
implementation and platform.
NumPy ndarray
NumPy provides the ndarray structure for
efficient numerical calculations and multidimensional data.
import numpy as np
arr = np.array([10, 20, 30, 40])
print(arr)
print(arr.dtype)
Indexing and Slicing
Positive indexing
Positive indexing starts from 0 and moves from left to right.
arr = [10, 20, 30, 40, 50]
print(arr[0])
print(arr[2])
print(arr[4])
103050
Negative indexing
Negative indexing accesses elements from the end of the list. The last element has index -1.
arr = [10, 20, 30, 40, 50]
print(arr[-1])
print(arr[-2])
5040
Array slicing
Slicing extracts a portion of a list using the syntax:
The start index is included, while the stop index is excluded. The step determines the interval between selected elements.
arr = [10, 20, 30, 40, 50, 60]
print(arr[1:4])
print(arr[:3])
print(arr[2:])
print(arr[::2])
print(arr[::-1])
[20, 30, 40]
[10, 20, 30]
[30, 40, 50, 60]
[10, 30, 50]
[60, 50, 40, 30, 20, 10]
How Arrays Work in Memory
Contiguous memory in traditional arrays
In a conventional fixed-size array, elements are stored in consecutive memory locations. If each element occupies the same number of bytes, its address can be calculated directly using its index.
This direct address calculation is one reason why array indexing takes O(1) time.
How Python lists work
A Python list is a dynamic array of object references. In CPython, the list maintains an allocated storage area containing references to Python objects. The objects themselves are stored separately.
Simplified illustration: the references are stored together, while the referenced Python objects are separate.
Dynamic resizing
Python lists can grow when elements are appended. The implementation may allocate additional capacity so that every append does not require resizing.
- Most append operations take O(1) amortized time.
- Occasional resizing can require O(n) time.
- Inserting at the beginning requires shifting elements.
Array Operations in Python
Accessing elements
arr = [10, 20, 30, 40, 50]
value = arr[2]
print(value)
Output: 30
Time: O(1)
Updating elements
arr = [10, 20, 30, 40]
arr[1] = 100
print(arr)
Output: [10, 100, 30, 40]
Time: O(1)
Traversing elements
Traversal visits all elements, usually using a for loop.
arr = [10, 20, 30, 40]
for value in arr:
print(value)
Time: O(n)
Insertion
arr = [10, 20, 30]
arr.append(40)
arr.insert(1, 15)
print(arr)
Output: [10, 15, 20, 30, 40]
Appending takes O(1) amortized time. Inserting at a particular position takes O(n) time in the general case because elements may need to shift.
Deletion
arr = [10, 20, 30, 40, 50]
arr.remove(30)
last = arr.pop()
print(last)
print(arr)
Output: 50
Remaining list: [10, 20, 40]
Removing a value requires a search and potentially shifting elements, so it takes O(n). Removing the last element with pop() is O(1) amortized.
Concatenation and merging
a = [10, 20, 30]
b = [40, 50]
result = a + b
print(result)
Output: [10, 20, 30, 40, 50]
Concatenating two lists of sizes n and m takes O(n + m) time and creates a new list.
Finding the length
arr = [10, 20, 30, 40]
print(len(arr))
Output: 4
Time: O(1)
Interactive Array Visualizer
Experiment with a Python-style list. You can traverse, search, insert and delete elements while observing how the array changes.
Current list: arr
Traversal
Search
Insertion
Deletion
Searching in Arrays
Linear search
Linear search examines elements sequentially until the target is found or all elements have been checked. It works with both sorted and unsorted data.
def linear_search(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
arr = [10, 20, 30, 40, 50]
print(linear_search(arr, 30))
2
Binary search
Binary search is an efficient searching algorithm that repeatedly divides a sorted search space into two halves.
def binary_search(arr, target):
left = 0
right = len(arr) - 1
while left <= right:
mid = (left + right) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
arr = [10, 20, 30, 40, 50]
print(binary_search(arr, 40))
3
Linear search vs binary search
| Comparison | Linear Search | Binary Search |
|---|---|---|
| Data requirement | Any order | Sorted |
| Best case | O(1) | O(1) |
| Worst case | O(n) | O(log n) |
| Approach | Sequential | Divide and conquer |
| Typical use | Small or unsorted data | Large sorted data |
Sorting Arrays
Sorting arranges elements in a particular order, such as ascending or descending. It is important for searching, ranking and many algorithmic problems.
Using sort()
arr = [40, 10, 50, 20, 30]
arr.sort()
print(arr)
Output: [10, 20, 30, 40, 50]
Descending order
arr = [40, 10, 50, 20, 30]
arr.sort(reverse=True)
print(arr)
Output: [50, 40, 30, 20, 10]
Using sorted()
Unlike sort(), sorted() creates and returns a new sorted list, leaving the original list unchanged.
arr = [30, 10, 20]
result = sorted(arr)
print(result)
print(arr)
Output: [10, 20, 30] and [30, 10, 20]
Common sorting algorithms
| Algorithm | Average Time | Worst Time |
|---|---|---|
| Bubble Sort | O(n²) | O(n²) |
| Selection Sort | O(n²) | O(n²) |
| Insertion Sort | O(n²) | O(n²) |
| Merge Sort | O(n log n) | O(n log n) |
| Quick Sort | O(n log n) | O(n²) |
| Python sort() | O(n log n) | O(n log n) |
Python’s built-in list sorting uses Timsort, a stable sorting algorithm that performs particularly well on partially ordered data.
Two-Dimensional Arrays
A two-dimensional array stores elements in rows and columns. In Python, it is commonly represented using a nested list.
matrix = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
]
print(matrix[1][2])
60
Visual representation
matrix[1][2] accesses row 1, column 2.
Traversing a 2D array
matrix = [
[10, 20, 30],
[40, 50, 60],
[70, 80, 90]
]
for row in matrix:
for value in row:
print(value, end=" ")
print()
Updating a matrix element
matrix[0][1] = 100
print(matrix[0])
Output: [10, 100, 30]
Creating a matrix correctly
Avoid using [[0] * 3] * 3 when you intend
to create independent rows. It repeats references to
the same inner list.
# Recommended approach
matrix = [[0 for col in range(3)]
for row in range(3)]
matrix[0][0] = 10
print(matrix)
[[10, 0, 0], [0, 0, 0], [0, 0, 0]]
Jagged arrays
A nested list does not have to contain equal-length rows. Such structures are sometimes called jagged or ragged arrays.
arr = [
[10, 20],
[30, 40, 50],
[60]
]
for row in arr:
print(row)
Important Python List Methods
| Method | Purpose | Example |
|---|---|---|
| append(x) | Add at end | arr.append(10) |
| insert(i,x) | Insert at index | arr.insert(0,10) |
| extend(iterable) | Add multiple values | arr.extend([10,20]) |
| remove(x) | Remove first matching value | arr.remove(10) |
| pop(i) | Remove and return an element | arr.pop() |
| index(x) | Find first matching index | arr.index(10) |
| count(x) | Count occurrences | arr.count(10) |
| sort() | Sort in place | arr.sort() |
| reverse() | Reverse in place | arr.reverse() |
| copy() | Shallow copy | arr.copy() |
| clear() | Remove all elements | arr.clear() |
Useful built-in functions
arr = [10, 20, 30, 40]
print(len(arr))
print(max(arr))
print(min(arr))
print(sum(arr))
print(sorted(arr, reverse=True))
4
40
10
100
[40, 30, 20, 10]
Time and Space Complexity of Arrays
Time complexity describes how the running time of an operation grows as the input size increases. Space complexity describes its additional memory requirements.
| Operation | Time Complexity |
|---|---|
| Index access | O(1) |
| Index update | O(1) |
| Traversal | O(n) |
| Linear search | O(n) |
| Binary search | O(log n) |
| Append | O(1) amortized |
| Insert at beginning | O(n) |
| Delete from beginning | O(n) |
| pop() at end | O(1) amortized |
| pop(i) | O(n) in general |
| remove(value) | O(n) |
| Membership (in) | O(n) |
| index() / count() | O(n) |
| Copy / slicing | O(n) / O(k) |
| Reverse | O(n) |
| Sort | O(n log n) |
| Concatenation | O(n + m) |
These are typical Python list complexities. Here, n represents the number of existing elements, m the size of another list, and k the number of elements in a slice. Sorting is O(n log n) in the worst case for Python’s built-in sort.
Understanding Big O notation
Important Array DSA Patterns
Many array problems can be solved efficiently by recognizing common algorithmic patterns instead of checking every possible combination.
Two pointers
Two pointers use two indexes to process elements from different positions. This is frequently used in sorted arrays, pair-sum problems and reversing.
def two_sum_sorted(arr, target):
left = 0
right = len(arr) - 1
while left < right:
total = arr[left] + arr[right]
if total == target:
return [left, right]
elif total < target:
left += 1
else:
right -= 1
return []
print(two_sum_sorted([1, 2, 4, 6, 8], 10))
Output: [1, 4]
Sliding window
Sliding window maintains a moving range of elements. It is useful for subarray problems involving fixed or variable window sizes.
def max_sum_subarray(arr, k):
if k <= 0 or k > len(arr):
return None
current = sum(arr[:k])
maximum = current
for i in range(k, len(arr)):
current += arr[i] - arr[i-k]
maximum = max(maximum, current)
return maximum
print(max_sum_subarray([2, 1, 5, 1, 3, 2], 3))
Output: 9
Prefix sum
Prefix sums store cumulative sums so that range-sum queries can be answered efficiently.
arr = [2, 4, 6, 8]
prefix = [0]
for value in arr:
prefix.append(prefix[-1] + value)
# Sum of elements from index 1 to 3
print(prefix[4] - prefix[1])
Output: 18
Kadane’s algorithm
Kadane’s algorithm finds the maximum sum of a non-empty contiguous subarray in linear time.
def max_subarray_sum(arr):
if not arr:
raise ValueError("Array must not be empty")
current = maximum = arr[0]
for value in arr[1:]:
current = max(value, current + value)
maximum = max(maximum, current)
return maximum
print(max_subarray_sum([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
Output: 6
Hashing and frequency counting
A dictionary or set can help solve array problems involving duplicates, frequencies and fast lookups.
arr = [10, 20, 10, 30, 20, 10]
frequency = {}
for value in arr:
frequency[value] = frequency.get(value, 0) + 1
print(frequency)
Output: {10: 3, 20: 2, 30: 1}
Binary search on answer
Binary search can also be applied to a sorted range of possible answers when a monotonic feasibility condition is available.
This technique appears in allocation, minimum capacity, scheduling and optimization problems.
Arrays in Data Science: NumPy
NumPy (Numerical Python) is a library for scientific and
numerical computing. Its central data structure is
ndarray, which supports multidimensional
homogeneous numerical data.
Creating a NumPy array
import numpy as np
arr = np.array([10, 20, 30, 40])
print(arr)
print(arr.shape)
print(arr.ndim)
print(arr.dtype)
NumPy array properties
shape: Dimensions of the array.ndim: Number of dimensions.dtype: Data type of elements.size: Total number of elements.itemsize: Bytes used by one element.
Vectorized operations
NumPy allows operations on entire arrays without explicitly writing a Python loop for each element.
import numpy as np
arr = np.array([10, 20, 30])
print(arr * 2)
print(arr + 5)
print(arr.mean())
[20 40 60]
[15 25 35]
20.0
NumPy broadcasting
Broadcasting allows compatible arrays with different shapes to participate in element-wise operations.
import numpy as np
arr = np.array([
[10, 20, 30],
[40, 50, 60]
])
result = arr + np.array([1, 2, 3])
print(result)
[[11 22 33]
[41 52 63]]
Reshaping arrays
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
matrix = arr.reshape(2, 3)
print(matrix)
[[1 2 3]
[4 5 6]]
Reshaping changes the array’s dimensions without changing its elements. The new shape must be compatible with the total number of elements.
Python list vs NumPy ndarray
| Feature | Python List | NumPy ndarray |
|---|---|---|
| Data types | Can be mixed | Usually one dtype |
| Dimensions | Nested lists | Native multidimensional |
| Math operations | Often require loops | Vectorized |
| Broadcasting | No built-in support | Supported |
| Common use | DSA and general Python | Numerical computing |
Applications of Arrays in Machine Learning
Feature vectors
A feature is an individual measurable characteristic used by a Machine Learning model. A feature vector contains multiple features for one sample.
features = [25, 50000, 2]
# Age: 25
# Salary: 50000
# Experience: 2 years
print(features)
Here, one sample is represented by three numerical features.
Dataset matrices
In supervised Machine Learning, the feature matrix is commonly represented by X. Each row represents a sample, while each column represents a feature.
import numpy as np
X = np.array([
[25, 50000, 2],
[30, 70000, 5],
[22, 35000, 1]
])
print(X.shape)
(3, 3)
This matrix contains three samples and three features.
Target values
The target variable, commonly represented by y, contains the expected output or label for each sample.
X = [
[25, 50000, 2],
[30, 70000, 5],
[22, 35000, 1]
]
y = [1, 1, 0]
Data preprocessing
Arrays are used in preprocessing operations such as normalization, scaling, filtering and transformation.
import numpy as np
features = np.array([10, 20, 30, 40, 50])
normalized = (
features - features.min()
) / (
features.max() - features.min()
)
print(normalized)
[0. 0.25 0.5 0.75 1. ]
Images as arrays
A digital image can be represented as a multidimensional array of pixel values.
- Grayscale image: (height, width)
- RGB image: (height, width, 3)
- Image batch: (batch, height, width, channels)
Each RGB pixel contains three channel values representing red, green and blue intensities.
Applications in AI
- Feature extraction and engineering.
- Numerical model inputs and outputs.
- Image processing and computer vision.
- Natural Language Processing embeddings.
- Recommendation system feature representations.
- Training and inference in neural networks.
Arrays, Matrices and Tensors
A tensor is a multidimensional data structure that generalizes scalars, vectors and matrices. Tensors are widely used in frameworks such as PyTorch and TensorFlow.
Tensor example in PyTorch
import torch
tensor = torch.tensor([
[10, 20, 30],
[40, 50, 60]
])
print(tensor)
print(tensor.shape)
print(tensor.ndim)
Image batch example
image_shape = (224, 224, 3)
batch_shape = (32, 224, 224, 3)
The second shape can represent 32 RGB images, each with dimensions of 224 × 224 pixels. Other frameworks and models may use a channel-first convention, such as (batch, channels, height, width).
Common Array Mistakes in Python
Index out of range
arr = [10, 20, 30]
print(arr[5])
Error: IndexError: list index out of range
The requested index does not exist. Valid positive indexes are 0, 1 and 2.
Confusing append() and extend()
a = [10, 20]
a.append([30, 40])
print(a)
Output: [10, 20, [30, 40]]
append() adds its argument as one element. extend() adds the elements from an iterable individually.
Copying lists incorrectly
a = [10, 20, 30]
b = a
b[0] = 100
print(a)
Output: [100, 20, 30]
Both variables refer to the same list. Use
b = a.copy() for a shallow copy.
For nested lists, a deep copy may be required.
Modifying a list while iterating
Removing elements from a list while iterating over it can cause elements to be skipped. Build a new filtered list or iterate over a copy when appropriate.
arr = [10, 20, 30, 40]
result = [x for x in arr if x != 20]
print(result)
Output: [10, 30, 40]
Important Array Practice Problems
Solve these problems to strengthen your understanding of array operations, algorithms and common DSA patterns.
Beginner level
- Find the largest element in an array.
- Find the smallest element.
- Calculate the sum and average.
- Count even and odd numbers.
- Reverse an array.
- Search for a given element.
- Count the occurrences of a value.
- Find the second-largest distinct element.
Intermediate level
- Remove duplicates from a sorted array.
- Move all zeros to the end.
- Rotate an array by k positions.
- Find the missing number.
- Merge two sorted arrays.
- Solve the Two Sum problem.
- Find the majority element.
- Find the intersection of two arrays.
Advanced level
- Find the maximum subarray sum.
- Find the product of array elements except self.
- Find the longest consecutive sequence.
- Find the maximum sum subarray of size k.
- Find the trapped rainwater.
- Find the median of two sorted arrays.
- Search in a rotated sorted array.
- Find the maximum area of a container.
Two-dimensional array problems
- Find the sum of each row and column.
- Transpose a matrix.
- Rotate a matrix by 90 degrees.
- Search in a sorted matrix.
- Print a matrix in spiral order.
- Find the diagonal sum.
Frequently Asked Array Interview Questions
What is an array in Python?
An array is an ordered collection of elements. Python lists are commonly used for array-based problems and support dynamic resizing.
Why does Python use zero-based indexing?
Zero-based indexing identifies the first element with index 0. It also makes offset calculations convenient in many programming systems.
What is the time complexity of array access?
Accessing an element of a Python list by index takes O(1) time.
What is the difference between a list and an array?
Python lists are flexible collections of object references. Traditional typed arrays store elements using a specified type, while NumPy arrays provide efficient multidimensional numerical operations.
Why is insertion at the beginning O(n)?
Existing elements generally need to shift to make room for the new element.
What is the difference between linear and binary search?
Linear search checks elements one by one. Binary search repeatedly halves a sorted search space.
What is a dynamic array?
A dynamic array can grow or shrink as elements are added or removed. Python lists behave like dynamic arrays in their underlying implementation.
What is a multidimensional array?
A multidimensional array organizes data across multiple dimensions, such as rows, columns and channels.
What is a feature vector in Machine Learning?
A feature vector is a collection of numerical characteristics representing one sample.
What is the difference between an array and a tensor?
An array is a general data structure for storing elements. A tensor is a mathematical and computational representation of multidimensional data, especially in Deep Learning.
Quick Revision: Arrays in Python
Array fundamentals
- Elements and indexes
- Zero-based and negative indexing
- Slicing and traversal
- Dynamic arrays and memory
Python operations
- Access, update, insert and delete
- Search, sort and merge
- List methods and built-in functions
- Copying and nested lists
DSA algorithms
- Linear and binary search
- Sorting algorithms
- Two pointers and sliding window
- Prefix sums and Kadane’s algorithm
Data Science and AI
- NumPy ndarray and broadcasting
- Feature vectors and datasets
- Image representations
- Multidimensional tensors
Arrays are one of the most important foundations of programming. A strong understanding of arrays helps you solve DSA problems, understand memory and algorithm complexity, process numerical data and build a foundation for Machine Learning, Deep Learning and Artificial Intelligence.