Last modified: Aug 16, 2026

Python Fixed-Size Array Guide

Python does not have a built-in fixed-size array type. But you can still create one. This guide shows you how.

Fixed-size arrays are useful when you know the exact number of elements in advance. They help with memory efficiency and predictability. In Python, you have a few good options.

We will explore three main approaches. First, using a list with a fixed length. Second, using the array module. Third, using NumPy's ndarray. Each method has its own strengths.

Why Use a Fixed-Size Array?

Fixed-size arrays prevent accidental growth. This can catch bugs early. They also use memory more efficiently than dynamic lists.

In performance-critical applications, fixed-size arrays reduce overhead. They allow for better cache locality. This means faster access times in loops.

Understanding these structures is key for system programming. It also helps with data analysis and scientific computing. Let's dive into the details.

Method 1: Using a Python List

A Python list is dynamic by default. But you can simulate a fixed size. Initialize it with placeholder values.

This method is simple and readable. It works well for small to medium-sized data. Here is an example.


# Create a fixed-size list of length 5
fixed_list = [0] * 5
print(fixed_list)  # Output: [0, 0, 0, 0, 0]

# Assign values
fixed_list[0] = 10
fixed_list[4] = 50
print(fixed_list)  # Output: [10, 0, 0, 0, 50]

This list has a fixed length of 5. But nothing stops you from appending. To enforce strictness, you can create a custom class.

Here is a better approach using a subclass. This prevents adding or removing items.


class FixedSizeList:
    def __init__(self, size):
        self._items = [0] * size
        self._size = size
    
    def __getitem__(self, index):
        return self._items[index]
    
    def __setitem__(self, index, value):
        self._items[index] = value
    
    def __len__(self):
        return self._size
    
    def append(self, value):
        raise AttributeError("Cannot append to a fixed-size list")

# Usage
arr = FixedSizeList(3)
arr[0] = 1
arr[1] = 2
arr[2] = 3
print(len(arr))  # Output: 3
# arr.append(4)  # This will raise an error

This custom class gives you control. It behaves like a real fixed-size array. For more on memory, check out our Python Array Memory Allocation Explained guide.

Method 2: Using the array Module

The array module provides typed arrays. These are more memory-efficient than lists. They store homogeneous data types.

You can create a fixed-size array by initializing with zeros. Then fill it with values. Here is how.


from array import array

# Create a fixed-size array of 4 integers
fixed_arr = array('i', [0] * 4)
print(fixed_arr)  # Output: array('i', [0, 0, 0, 0])

# Assign values
fixed_arr[0] = 5
fixed_arr[3] = 20
print(fixed_arr)  # Output: array('i', [5, 0, 0, 20])

The type code 'i' stands for signed integer. You can use other codes like 'f' for float. This makes the array compact.

However, array still allows appending. You can override this behavior. Or simply avoid calling append.

For type safety, this module is great. It ensures all elements are of the same type. This is useful for binary data processing.

Method 3: Using NumPy Arrays

NumPy is the standard for numerical computing in Python. Its ndarray supports fixed-size arrays natively. This is the most powerful option.

NumPy arrays are fast and memory-efficient. They support multi-dimensional data. Here is a basic example.


import numpy as np

# Create a fixed-size NumPy array of 5 floats
np_arr = np.zeros(5, dtype=float)
print(np_arr)  # Output: [0. 0. 0. 0. 0.]

# Assign values
np_arr[0] = 1.5
np_arr[4] = 9.9
print(np_arr)  # Output: [1.5 0.  0.  0.  9.9]

Once created, the size is fixed. You cannot change the shape. This is enforced by NumPy.

NumPy also offers many built-in functions. You can perform math operations easily. This makes it ideal for scientific applications.

If you need to check for elements, see our Python Array Contains: Check if Element Exists guide. It works with NumPy too.

Performance Comparison

Let's compare the three methods. Lists are flexible but slower. The array module is faster and compact. NumPy is the fastest for large data.

Here is a simple benchmark. We create a million-element array and sum it.


import time
from array import array
import numpy as np

# List
start = time.time()
lst = [1] * 1_000_000
total = sum(lst)
print(f"List time: {time.time() - start:.4f}s")

# Array module
start = time.time()
arr = array('i', [1] * 1_000_000)
total = sum(arr)
print(f"Array module time: {time.time() - start:.4f}s")

# NumPy
start = time.time()
np_arr = np.ones(1_000_000, dtype=int)
total = np.sum(np_arr)
print(f"NumPy time: {time.time() - start:.4f}s")

List time: 0.0450s
Array module time: 0.0380s
NumPy time: 0.0020s

NumPy is significantly faster. It uses optimized C code. For large datasets, this matters a lot.

The array module is a good middle ground. It is faster than lists but slower than NumPy. Choose based on your needs.

When to Use Each Method

Use a plain list for small, simple tasks. It is easy to read and debug. You can convert it later if needed.

Use the array module for memory efficiency. It is great for storing homogeneous data. It works well with binary files.

Use NumPy for heavy numerical work. It is essential for data science and machine learning. It provides many advanced features.

For type casting, check our Python Array Type Casting Guide. It explains how to change data types safely.

Common Pitfalls

One mistake is trying to resize a fixed array. This raises an error. Always create a new array if you need a different size.

Another issue is index out of bounds. Accessing an index beyond the size throws an exception. Always check the length first.

For lists, remember that [0] * n creates a list of references. For mutable objects, this can be tricky. Use list comprehension for safety.


# Avoid this (same object references)
list_of_lists = [[]] * 3
list_of_lists[0].append(1)
print(list_of_lists)  # Output: [[1], [1], [1]]

# Use this instead
list_of_lists = [[] for _ in range(3)]
list_of_lists[0].append(1)
print(list_of_lists)  # Output: [[1], [], []]

This is a classic Python gotcha. Be aware of it when using fixed-size lists.

Working with Fixed-Size Arrays

You can iterate over fixed-size arrays easily. Use a for loop or a while loop. Here is a quick example.


import numpy as np

arr = np.array([10, 20, 30, 40])

# For loop
for value in arr:
    print(value * 2)

# While loop
i = 0
while i < len(arr):
    print(arr[i] + 1)
    i += 1

For more on loops, see our Python Array Iteration: For vs While Loop guide. It covers best practices.

You can also convert arrays to lists. This is useful for compatibility. Use the tolist() method for NumPy.


import numpy as np

np_arr = np.array([1, 2, 3])
list_from_np = np_arr.tolist()
print(list_from_np)  # Output: [1, 2, 3]

For more conversion tips, check our Python Array to List Conversion Guide.

Conclusion

Fixed-size arrays in Python are achievable with several methods. The list approach is simple. The array module offers efficiency. NumPy provides the best performance.

Choose the method that fits your project. Consider the data size and complexity. Always test for edge cases.

Remember to handle errors gracefully. Use bounds checking where needed. This prevents crashes and bugs.

With these tools, you can write efficient Python code. Fixed-size arrays are a valuable addition to your toolkit. Start using them today.