Explain Codes LogoExplain Codes Logo

Initialising an array of fixed size in Python

python
list-comprehensions
numpy
performance
Anton ShumikhinbyAnton Shumikhin·Nov 29, 2024
TLDR

Here's how to initialize a fixed-size array in Python:

fixed_array = [0] * 10 # 10 is array size. Will this leave an empty void in your life? No, it'll leave 10.

This code creates a list of 10 elements, all initialized to 0.

Beyond the obvious: advanced techniques

Just creating a list with default values may not be enough for you. Read on to discover more advanced ways of initializing arrays in Python.

NumPy to the rescue: efficient storage of numerical data

When dealing with numerical data, consider skipping Python's list and moving straight to NumPy:

import numpy as np # numpy.zeros: your friendly neighborhood zero-filled array zero_array = np.zeros(10) # numpy.empty: like a mysterious black box—it's there but uninitialized empty_array = np.empty(10)

These NumPy methods are much like ordering a tailor-made suit—with dtype, you get optimized performance tailored to your specific numeric data.

List comprehensions: for when you need full control

For custom initialization or when working with expressions, turn to list comprehensions:

# A list comprehension, feel the power in your brackets! custom_array = [expression(i) for i in range(10)]

Multi-dimensional arrays: handle with care

For multi-dimensional arrays, steer clear of list multiplication—it's a sneaky way to fill your array with references to the same list:

# This is the dangerous way, might lead to a clone apocalypse unsafe_2D_array = [[None] * cols] * rows # Clone-free way, every row is unique, just like you. safe_2D_array = [[None for _ in range(cols)] for _ in range(rows)]

Traps and tricks: Playing smart with arrays

No need to impress: don’t overcomplicate

While working with NumPy can make you feel cool and resourceful, don't use it unless you're working with bulky arrays or doing serious number crunching. Python's list is usually enough and more versatile with data types.

Stay safe: watch out for shallow copies

A common rookie mistake is using list multiplication to generate 2D arrays. This will clone references to the same list, leading to surprising and unwanted results when you modify one element.

Plan ahead: pre-allocate wisely

Pre-assigning array size with None like a parking space for your data is a good strategy. However, keep in mind that if you're immediately assigning values, pre-allocation might be an unnecessary step.

Choose wisely: pick the right tool

NumPy is like a swiss army knife when it comes to array performance. But remember, every tool has its purpose, and for more flexible type handling, Python's own lists are still king.