Python
Array
Fixed Size
Initialization
Duplicate

Initialising an array of fixed size in Python

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Python does not have a built-in fixed-size array type like C or Java. Instead, Python provides lists (dynamic arrays), the array module (typed arrays), and NumPy arrays (fixed-size, high-performance). Each approach has different trade-offs for memory efficiency, type safety, and performance.

Method 1: List Multiplication

The simplest way to create a list of a fixed size filled with a default value:

python
1# Initialize with zeros
2zeros = [0] * 10
3print(zeros)  # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
4
5# Initialize with None
6empty = [None] * 5
7print(empty)  # [None, None, None, None, None]
8
9# Initialize with empty strings
10names = [''] * 3
11print(names)  # ['', '', '']

Warning: This creates references for mutable objects, not independent copies:

python
1# BAD: all inner lists are the SAME object
2matrix = [[0] * 3] * 3
3matrix[0][0] = 1
4print(matrix)  # [[1, 0, 0], [1, 0, 0], [1, 0, 0]] — all rows changed!
5
6# GOOD: use list comprehension for independent objects
7matrix = [[0] * 3 for _ in range(3)]
8matrix[0][0] = 1
9print(matrix)  # [[1, 0, 0], [0, 0, 0], [0, 0, 0]] — only first row changed

Method 2: List Comprehension

More flexible initialization with computed values:

python
1# Squares
2squares = [i**2 for i in range(10)]
3print(squares)  # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
4
5# Fixed size with index-based values
6arr = [i * 0.5 for i in range(5)]
7print(arr)  # [0.0, 0.5, 1.0, 1.5, 2.0]
8
9# Fixed size with default factory
10from collections import defaultdict
11arr = [dict() for _ in range(3)]  # 3 independent empty dicts

Method 3: array Module (Typed)

Python's array module provides compact typed arrays:

python
1from array import array
2
3# Integer array
4int_arr = array('i', [0] * 10)     # signed int
5print(int_arr)  # array('i', [0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
6
7# Float array
8float_arr = array('d', [0.0] * 5)  # double
9print(float_arr)  # array('d', [0.0, 0.0, 0.0, 0.0, 0.0])
10
11# Byte array
12byte_arr = array('b', [0] * 8)     # signed char

Type codes:

CodeTypeSize (bytes)
'b'signed char1
'i'signed int2-4
'l'signed long4-8
'f'float4
'd'double8

Method 4: NumPy Arrays (Best for Numeric Data)

NumPy provides true fixed-size, contiguous-memory arrays:

python
1import numpy as np
2
3# Zeros
4zeros = np.zeros(10)
5print(zeros)  # [0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
6
7# Zeros with specific type
8int_zeros = np.zeros(10, dtype=np.int32)
9
10# Ones
11ones = np.ones(5)
12
13# Empty (uninitialized — faster, but values are garbage)
14empty = np.empty(10)
15
16# Filled with a specific value
17fives = np.full(10, 5)
18print(fives)  # [5 5 5 5 5 5 5 5 5 5]
19
20# 2D arrays
21matrix = np.zeros((3, 4))    # 3 rows, 4 columns
22cube = np.zeros((2, 3, 4))   # 3D array
23
24# Range-based
25arr = np.arange(0, 10, 0.5)  # [0.0, 0.5, 1.0, ..., 9.5]
26arr = np.linspace(0, 1, 5)   # [0.0, 0.25, 0.5, 0.75, 1.0]

Method 5: bytearray (For Bytes)

python
1# Fixed-size byte array initialized to zeros
2buf = bytearray(1024)
3print(len(buf))    # 1024
4print(buf[:5])     # bytearray(b'\x00\x00\x00\x00\x00')
5
6buf[0] = 0xFF

Performance Comparison

python
1import sys
2
3n = 1000000
4
5# Memory usage
6list_arr = [0] * n
7numpy_arr = np.zeros(n, dtype=np.int64)
8array_arr = array('l', [0] * n)
9
10print(f"List:  {sys.getsizeof(list_arr):>12,} bytes")   # ~8,000,056
11print(f"NumPy: {numpy_arr.nbytes:>12,} bytes")           # ~8,000,000
12print(f"array: {array_arr.buffer_info()[1] * 8:>12,} bytes")  # ~8,000,000

Lists have significant per-element overhead (~56 bytes per int object + 8 bytes per pointer) compared to NumPy and array (8 bytes per int64).

Common Pitfalls

  • Mutable default trap: [[]] * n creates n references to the same inner list. Always use [[] for _ in range(n)] for mutable elements.
  • Lists are not fixed-size: Python lists can grow with append(). If you need strict fixed-size enforcement, use NumPy arrays or wrap a list in a class that prevents resizing.
  • NumPy empty vs zeros: np.empty() is faster but contains uninitialized (garbage) data. Always use np.zeros() unless you will immediately overwrite every element.
  • Type enforcement: Lists accept any type; array and NumPy enforce types. Inserting a string into an array('i', ...) raises TypeError.
  • Memory layout: NumPy arrays store data contiguously in memory, enabling SIMD and cache-friendly operations. Lists store pointers to scattered objects.

Summary

  • Use [value] * n for quick list initialization with immutable defaults
  • Use list comprehensions for mutable elements: [[] for _ in range(n)]
  • Use numpy.zeros(n) or numpy.full(n, value) for numeric fixed-size arrays
  • Use array.array for typed, compact arrays without the NumPy dependency
  • Lists are dynamic — Python has no built-in mechanism to prevent resizing

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.