DocsStation
DSA with Python

Arrays in Python: Complete Guide for DSA, Data Science, AI and Machine Learning

By csestudy247 Updated December 2, 2026 17 min read
17 min read
FOUNDATIONS

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.

Important Python distinction Python’s built-in 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.
Python example
arr = [10, 20, 30, 40, 50]

print(arr)
Output [10, 20, 30, 40, 50]
CORE CONCEPT

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

10Index 0
20Index 1
30Index 2
40Index 3
50Index 4

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

102030

A sequence of elements arranged in one dimension.

Two-dimensional array

1020 3040

Elements organized into rows and columns.

Multidimensional array

3D

Data represented across three or more dimensions.

PYTHON IMPLEMENTATION

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))
Output [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])
Output 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)
Which should you learn? Start with Python lists for DSA. Learn the array module to understand typed arrays, then study NumPy for numerical computing and Machine Learning.
ELEMENT ACCESS

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])
Output 103050

Negative indexing

Negative indexing accesses elements from the end of the list. The last element has index -1.

100 / -5
201 / -4
302 / -3
403 / -2
504 / -1
arr = [10, 20, 30, 40, 50]

print(arr[-1])
print(arr[-2])
Output 5040

Array slicing

Slicing extracts a portion of a list using the syntax:

list[start : stop : step]

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])
Output [20, 30, 40] [10, 20, 30] [30, 40, 50, 60] [10, 30, 50] [60, 50, 40, 30, 20, 10]
Complexity: Reading an individual list element is O(1). Creating a slice containing k elements takes O(k) time and O(k) additional space.
INTERNAL WORKING

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.

Address(i) = Base Address + (i × Element Size)

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.

Conceptual Python list storage
Reference 0
Reference 1
Reference 2
Reference 3
↓
10
20
30
40

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.
CORE OPERATIONS

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)

LEARN BY DOING

Interactive Array Visualizer

Experiment with a Python-style list. You can traverse, search, insert and delete elements while observing how the array changes.

Array Playground

Current list: arr

Ready. Select an operation to begin.

Traversal

Search

Insertion

Deletion

What to observe Insertion at a middle index moves subsequent elements to the right. Deletion closes the gap by shifting subsequent elements to the left.
ORDERING 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 SortO(n²)O(n²)
Selection SortO(n²)O(n²)
Insertion SortO(n²)O(n²)
Merge SortO(n log n)O(n log n)
Quick SortO(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.

MULTIDIMENSIONAL 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])
Output 60

Visual representation

102030
405060
708090

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)
Output [[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)
Element access: O(1) Full traversal: O(rows × columns) for a rectangular matrix
PYTHON REFERENCE

Important Python List Methods

MethodPurposeExample
append(x)Add at endarr.append(10)
insert(i,x)Insert at indexarr.insert(0,10)
extend(iterable)Add multiple valuesarr.extend([10,20])
remove(x)Remove first matching valuearr.remove(10)
pop(i)Remove and return an elementarr.pop()
index(x)Find first matching indexarr.index(10)
count(x)Count occurrencesarr.count(10)
sort()Sort in placearr.sort()
reverse()Reverse in placearr.reverse()
copy()Shallow copyarr.copy()
clear()Remove all elementsarr.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))
Output 4 40 10 100 [40, 30, 20, 10]
ALGORITHM ANALYSIS

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 accessO(1)
Index updateO(1)
TraversalO(n)
Linear searchO(n)
Binary searchO(log n)
AppendO(1) amortized
Insert at beginningO(n)
Delete from beginningO(n)
pop() at endO(1) amortized
pop(i)O(n) in general
remove(value)O(n)
Membership (in)O(n)
index() / count()O(n)
Copy / slicingO(n) / O(k)
ReverseO(n)
SortO(n log n)
ConcatenationO(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

O(1)Constant
O(log n)Logarithmic
O(n)Linear
O(n log n)Linearithmic
O(n²)Quadratic
DSA PROBLEM SOLVING

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.

NUMERICAL COMPUTING

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())
Output [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)
Output [[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)
Output [[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

FeaturePython ListNumPy ndarray
Data typesCan be mixedUsually one dtype
DimensionsNested listsNative multidimensional
Math operationsOften require loopsVectorized
BroadcastingNo built-in supportSupported
Common useDSA and general PythonNumerical computing
ARTIFICIAL INTELLIGENCE

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)
Output (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)
Output [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.
DEEP LEARNING

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.

0DScalar — a single value
1DVector — a sequence of values
2DMatrix — rows and columns
3D+Higher-dimensional tensor

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).

LEARNING CHECKPOINT

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]

PRACTICE AND APPLICATION

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.
INTERVIEW PREPARATION

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.

FINAL REVIEW

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.

Python Arrays – Complete Learning Guide

Learn • Practice • Visualize • Build

Scroll to Top