Skip to content
Concept ยท Data Structures and Algorithms

Array in data structure: operations, memory layout and code

Younus FardeenBy Younus FardeenUpdated 1 Dec 20268 min read
Short answer

An array is a collection of items of the same type stored in contiguous memory, where each item is reached by its index. Reading or writing by index is O(1). Inserting or deleting in the middle or at the front is O(n) because later items must shift. Appending at the end is O(1) amortised.

On this pageWhat is an array and why is indexing O(1)?Python list vs array module vs NumPyInsert and delete cost: measured1D and 2D arraysCommon interview problems on arraysFrequently asked questions

This page explains the array as a machine sees it, then measures what its operations cost in Python 3.9.6 (run on 1 December 2026). It is for students preparing for DSA rounds and for anyone who has used lists for a year and never asked how they work.

For where arrays are used in practice, see applications of array in data structure. For the alternative, see array vs linked list.

What is an array and why is indexing O(1)?

An array stores items of one type side by side in memory. If the first item is at address base and each item takes size bytes, item i is at base + i * size. One multiplication and one addition, whatever the value of i, so access is O(1). That single fact explains every other cost on this page.

OperationTimeWhy
Read or write a[i]O(1)Address is computed from the index
Append at the endO(1) amortisedSpare capacity; occasional resize copies everything
Insert at the front or middleO(n)Later items shift right
Delete at the front or middleO(n)Later items shift left
Delete at the endO(1)Nothing moves
Search an unsorted arrayO(n)Check each item
Search a sorted arrayO(log n)Binary search

Classic C arrays have a fixed size set at creation. Python, Java's ArrayList and JavaScript arrays are dynamic arrays: they keep spare room and, when full, allocate a bigger block and copy. That copy is rare, so append averages out to O(1). The Python wiki time complexity table lists list append as amortised O(1) and insert as O(n).

Python list vs array module vs NumPy

Three things get called an array in Python, and they are different.

listarray.arrayNumPy ndarray
Item typesAnything, mixedOne C type (for example i for 4-byte int)One dtype (for example int64)
StoragePointers to separate objectsRaw values packed togetherRaw values packed together
DimensionsNested lists1D onlyN-dimensional
Best forGeneral programs, interviewsCompact 1D numbersNumeric work, data science, vector maths
InstallBuilt inBuilt inpip install numpy

This matters for memory. A list holds a pointer to each Python object, so a million integers cost the pointer array plus a million int objects. An array('i') holds the raw 4-byte values. Run it:

import sys
from array import array

lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr = array("i", lst)
print("list :", sys.getsizeof(lst), "bytes for the list object itself, plus", len(lst), "pointers to int objects")
print("array:", sys.getsizeof(arr), "bytes in total, item size", arr.itemsize)
print(arr.typecode, arr.itemsize, arr[3])

big = list(range(1_000_000))
packed = array("i", big)
print("list of 1M:", sys.getsizeof(big) // 1_000_000, "bytes per slot (pointers only)")
print("array of 1M:", sys.getsizeof(packed) // 1_000_000, "bytes per item")
list : 152 bytes for the list object itself, plus 10 pointers to int objects
array: 104 bytes in total, item size 4
i 4 4
list of 1M: 8 bytes per slot (pointers only)
array of 1M: 4 bytes per item

The list reports about 8 bytes per slot for pointers alone (the integer objects are extra), while the array uses 4 bytes per item in total. For DSA interviews you can use lists as arrays. When someone asks for a real array with a fixed type, this is the distinction they want. For Python-specific questions on lists, see Python interview questions.

Insert and delete cost: measured

The table above says front operations are O(n) and end operations are O(1). Here is a measurement on a list of one million items, repeating each operation 200 times.

import time

n = 1_000_000
a = list(range(n))

def clock(label, op, reps=200):
    t = time.perf_counter()
    for _ in range(reps):
        op()
    ms = (time.perf_counter() - t) * 1000
    print(f"{label:22s} x{reps}: {ms:8.2f} ms")

clock("insert(0, x)  front", lambda: a.insert(0, -1))
clock("pop(0)        front", lambda: a.pop(0))
clock("append(x)     end", lambda: a.append(-1))
clock("pop()         end", lambda: a.pop())
clock("a[500000]     read", lambda: a[500_000])
insert(0, x)  front    x200:    81.19 ms
pop(0)        front    x200:    32.42 ms
append(x)     end      x200:     0.02 ms
pop()         end      x200:     0.02 ms
a[500000]     read     x200:     0.02 ms

On this run, 200 front inserts took about 100 ms and 200 front deletes about 50 ms, while 200 appends, end deletes and middle reads each took a few hundredths of a millisecond. Timings vary between machines and runs, so trust the ratio, not the numbers: front operations are thousands of times slower here, and the gap grows with the list. Each front insert moves a million pointers. If you need to add and remove at the front often, use collections.deque, as in the queue page.

1D and 2D arrays

A 1D array is a single row of items. A 2D array is a table with rows and columns, written grid[row][col]. Memory is still one line, so languages lay the rows out one after another (row-major order; C, Python and NumPy by default). Reading row by row therefore walks memory in order, which is faster than jumping down a column.

grid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(grid[1][2])                       # row 1, column 2
print([row[0] for row in grid])         # first column
print([list(col) for col in zip(*grid)])  # transpose

# common trap: rows that are the same object
bad = [[0] * 3] * 3
bad[0][0] = 9
print(bad)
good = [[0] * 3 for _ in range(3)]
good[0][0] = 9
print(good)
6
[1, 4, 7]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
[[9, 0, 0], [9, 0, 0], [9, 0, 0]]
[[9, 0, 0], [0, 0, 0], [0, 0, 0]]

The last two lines are the most common 2D bug. [[0] * 3] * 3 copies the reference to one row three times, so changing one cell changes all three rows. The list comprehension builds three separate rows.

NumPy stores a 2D array as one block and tracks how many bytes to step along each axis:

import numpy as np

a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape, a.dtype, a.strides)       # strides in bytes: row step, column step
print(a.sum(axis=0), a.sum(axis=1))
print(a.T.shape, a[:, 1])
print(a.flags["C_CONTIGUOUS"])
(2, 3) int64 (24, 8)
[5 7 9] [ 6 15]
(3, 2) [2 5]
True

A 2 by 3 array of 8-byte integers has strides (24, 8): 24 bytes to the next row, 8 bytes to the next column. The sums over axis 0 and axis 1 give column and row totals. The row sums are 6 and 15.

Common interview problems on arrays

Most array questions fall into a few patterns: hash map lookup, two pointers, sliding window, prefix sums and in-place rewriting. Three that appear constantly:

def two_sum(nums, target):
    seen = {}
    for i, x in enumerate(nums):
        if target - x in seen:
            return seen[target - x], i
        seen[x] = i

def max_subarray(nums):          # Kadane's algorithm
    best = cur = nums[0]
    for x in nums[1:]:
        cur = max(x, cur + x)
        best = max(best, cur)
    return best

def rotate(nums, k):
    k %= len(nums)
    nums[:] = nums[-k:] + nums[:-k]
    return nums

print(two_sum([2, 7, 11, 15], 9))
print(max_subarray([-2, 1, -3, 4, -1, 2, 1, -5, 4]))
print(rotate([1, 2, 3, 4, 5, 6, 7], 3))
(0, 1)
6
[5, 6, 7, 1, 2, 3, 4]
  • Two sum: one pass with a dictionary of values seen so far. O(n) time, O(n) space, instead of the O(n squared) double loop. See hashmap explained.
  • Maximum subarray (Kadane): keep the best sum ending here, either extend or restart. O(n) time, O(1) space. The sample input gives 6.
  • Rotate by k: reduce k modulo length, then slice. Interviewers may then ask for O(1) extra space, which needs three reversals.

Practise next: remove duplicates from a sorted array in place, merge two sorted arrays, product of array except self, and best time to buy and sell a stock. If a question asks for the best time, first write the double loop and its cost, then improve it; the habit of counting cost is covered in time complexity and Big O. More questions are in DSA interview questions, and the order of topics is on the data structures and algorithms learning path.

const a = [10, 20, 30];
a.push(40);          // amortised O(1)
a.unshift(5);        // shifts everything: O(n)
console.log(a, a.length, a[2]);

Frequently asked questions

What is an array in a data structure?

An array is a collection of items of the same type stored in contiguous memory and accessed by a zero-based index. Because the address of any item is computed directly from its index, reading or writing one item takes constant time, O(1).

What is the time complexity of array operations?

Access by index is O(1). Search in an unsorted array is O(n). Insertion or deletion at the front or middle is O(n) because items shift. Appending or removing at the end is O(1), amortised for appends in a dynamic array.

What is the difference between 1D and 2D arrays?

A 1D array is a single row of items addressed by one index. A 2D array is a table addressed by a row index and a column index. In memory both are one continuous block; a 2D array is stored row after row in row-major order.

Is a Python list an array?

A Python list is a dynamic array of pointers to objects, so it behaves like an array for indexing and append. It can hold mixed types, which a true array cannot. For packed numbers, the array module or NumPy store raw values.

Why is inserting into an array slow?

To insert at position i, every item from i onward must move one place to make room. For n items that is up to n moves, so O(n). Inserting at the end needs no moves, which is why appending is cheap.

When should I use an array instead of a linked list?

Use an array when you read by index or scan items in order, which is most of the time. Use a linked list only when you already hold a node and insert or remove next to it often. The comparison page linked above has a decision table.

Learn this with mentors

Programmes for builders and engineers with admissions open: live classes, mentors and project work.

Continue learning

Explainer

Applications of array

Where arrays are used and the patterns that solve array problems.

3 min read
Concept

Array vs linked list

Decision table, measured timings, cache locality and interview traps

6 min read
Explainer

HashMap explained

How hashing, buckets and collisions work, with Python, JS and Java.

4 min read