Open In App

How to create an empty and a full NumPy array?

Last Updated : 28 Jan, 2025
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Creating arrays is a basic operation in NumPy.

  • Empty array: This array isn’t initialized with any specific values. It’s like a blank page, ready to be filled with data later. However, it will contain random leftover values in memory until you update it.
  • Full array: This is an array where all the elements are set to the same specific value right from the start. It’s like a sheet filled with one number everywhere.

NumPy provides simple functions numpy.empty() for empty arrays numpy.full() empty arrays and full arrays.

import numpy as np

# Create an empty array of shape (3, 4)
empty_array = np.empty((3, 4))
print("Empty Array:\n", empty_array)

# Create a full array of shape (3, 3) filled with the value 5
full_array = np.full((3, 3), 5)
print("Full Array:\n", full_array)

Output
Empty Array:
 [[4.63714601e-310 0.00000000e+000 0.00000000e+000 0.00000000e+000]
 [0.00000000e+000 0.00000000e+000 0.00000000e+000 0.00000000e+000]
 [0.00000000e+000 0.00000000e+000 0.00000000e+000 0....

How to Create an Empty NumPy Array?

Creating an empty array is useful when you need a placeholder for future data that will be populated later. It allocates space without initializing it, which can be efficient in terms of performance.

  • Use the np.empty() function.
  • Specify the shape of the array as a tuple.
  • Optionally, define the data type using the dtype parameter.
import numpy as np

empty_array_2d = np.empty((3, 4))
print(empty_array_2d)

Output
[[1.13473609e-313 0.00000000e+000 2.10077583e-312 6.79038654e-313]
 [2.22809558e-312 2.14321575e-312 2.35541533e-312 6.79038654e-313]
 [2.22809558e-312 2.14321575e-312 2.46151512e-312 2.41907520e-312]...

How to Create a Full NumPy Array?

A full array is ideal when you need an array initialized with a specific value, such as zeros or ones, which is common in many mathematical computations. Steps:

  • Use the np.full() function.
  • Pass the desired shape and fill value.
  • Optionally, specify the data type.
import numpy as np

full_array_2d = np.full((3, 4), 5)
print(full_array_2d)

Output
[[5 5 5 5]
 [5 5 5 5]
 [5 5 5 5]]

Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg