Labs ICT
Pro Login

Zeros, Ones & Empty

Creating arrays filled with specific values.

Zeros, Ones & Empty

Sometimes you need to create arrays with specific values without manually typing them. NumPy has some handy functions for this. Think of it like having templates for your arrays.

Creating Arrays of Zeros

np.zeros() creates an array filled with zeros. You specify the shape as a tuple.


import numpy as np

zeros_1d = np.zeros(5)
zeros_2d = np.zeros((3, 4))

print(f"1D Zeros: {zeros_1d}")
print(f"2D Zeros:\n{zeros_2d}")
    

Notice the dtype is float64 by default. That's because zeros are integers but NumPy assumes you might want decimal numbers.

Creating Arrays of Ones

Similarly, np.ones() creates arrays filled with ones.


import numpy as np

ones_1d = np.ones(4)
ones_2d = np.ones((2, 3))

print(f"1D Ones: {ones_1d}")
print(f"2D Ones:\n{ones_2d}")
    

I definitely used np.ones() a lot when I was learning. It's great for initializing arrays or creating masks.

Empty Arrays

np.empty() creates an array without initializing values. It's faster but contains garbage data.


import numpy as np

empty_arr = np.empty((2, 3))
print(f"Empty array:\n{empty_arr}")
    

Use empty when you know you'll fill the array immediately. It's a performance optimization.

Filling with a Specific Value

np.full() lets you fill an array with any value you want.


import numpy as np

full_arr = np.full((3, 3), 7)
print(f"Full of sevens:\n{full_arr}")
    

One thing that confused me at first was when to use each function. Use zeros/ones for initialization, empty for performance, and full for specific values.

Try it Yourself →

Key Takeaways

  • np.zeros() creates arrays of zeros with specified shape
  • np.ones() creates arrays of ones
  • np.empty() creates uninitialized arrays (faster)
  • np.full() fills an array with a specific value