Explain Codes LogoExplain Codes Logo

Numpy Array Initialization (Fill With Identical Values)

python
numpy
array-initialization
performance-tips
Anton ShumikhinbyAnton Shumikhin·Jan 11, 2025
TLDR

Initialize a whole array with a constant value in NumPy using np.full(). Set the shape of the array and the fill_value as parameters.

import numpy as np # Okay, okay 9s it is! You've asked for 9s mate, there ya go! array = np.full((2, 2), 9)

Output: [[9 9] [9 9]] - like a platter of your favourite 9s, served hot!

Other Ways: We Got Plenty!

Empty, but filled? [Yeah, kind of schrödinger thingy 😉]

For large arrays, np.empty() combined with fill() lands a pretty fast way to get your arrays filled up:

# Hey look, treasure troves everywhere! Oops, they’re empty! large_array = np.empty((10, 10)) # No worries, fill 'em up with 7s you said? Okay then! large_array.fill(7)

Here we first allocate memory using np.empty() without initializing it and then fill it up. Faster and furious(er)?

Slices all over: [No, not pizzas. Arrays, man!]

# Trazan call! Empty array coming up! Assemble! array = np.empty((2, 2)) # All right my sliced friends, stand in line and take your 9s, now! array[:] = 9

Just another efficient way to initialize your moderate-sized arrays. Take a slice, have a byte!

None shall pass: [Unless you're None]

For those none-believers - ahem, I mean None values. We have something for them too:

# None, you say? Alright, everyone make room for None! array_with_none = np.full((3, 3), None, dtype=object)

This trick ensures None values are handled correctly. No None left behind!

Speed Talk: Performance Tips

Broadcasting for the win: number-crunching, literally!

# Just broadcasting some zeros, wait, now they're eights, magic! array_broadcasted = np.zeros((5, 5)) + 8

This exploitation of broadcasting can leapfrog performance without resorting to explicit loops.

Use performance-tooling libraries, e.g., perfplot, to benchmark various methods, especially if you're working on bigger datasets.

Snapshot: Comparison Table

MethodBest ForInitialization StylePerformance
np.full()Any sizeImmediateHigh
np.empty().fill()Larger sizeTwo-StepVery High
Slice notation [:]Small-MediumImmediateHigh
Loops/np.repeat()Just Don'tIterativeLow

Yes, everything else is slower than np.empty().fill(). No, we don't sell turtles here!

Quick note: Data Types and Values

Beware of data types (dtype). For object arrays or complex data structures, specifying dtype prevents "I-didn't-see-that-coming" moments.

Practical tips and tricks

We love NumPy's array initialization— useful everywhere, from tuning parameters in simulation to creating masks for image processing

Behold: Matching dimensions:

other_array = np.random.rand(3, 4) matching_array = np.full(other_array.shape, 3.14)

Creating arrays with exactly the same dimensions as others. Pi for everyone!

Speed matters: Performance Tuning

When speed is the name of the game, trial different initialization methods for the best memory footprint vs computation time balance.