w3resource

NumPy: Create an empty and a full array


Create Empty and Full Array

Write a NumPy program to create an empty and full array.

Python NumPy: Create an empty and a full array

Sample Solution:-

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating an empty array of shape (3, 4) using np.empty()
x = np.empty((3, 4))

# Printing the empty array 'x'
print(x)

# Creating a filled array of shape (3, 3) with all elements as 6 using np.full()
y = np.full((3, 3), 6)

# Printing the filled array 'y'
print(y)

Sample Output:

[[  6.93643969e-310   8.76783124e-317   6.93643881e-310   6.79038654e-31
3]                                                                      
 [  2.22809558e-312   2.14321575e-312   2.35541533e-312   2.42092166e-32
2]                                                                      
 [  7.46824097e-317   9.08479214e-317   2.46151512e-312   2.41907520e-31
2]]                                                                     
[[6 6 6]                                                                
 [6 6 6]                                                                
 [6 6 6]]

Explanation:

In the above code –

x = [10, 20, 30]: Defines a list called ‘x’ with three integer elements.

x = np.append(x, [[40, 50, 60], [70, 80, 90]]): The np.append() function is used to append two lists of three elements each to the original list ‘x’. The resulting object is converted into a NumPy array and stored back into ‘x’.


For more Practice: Solve these Related Problems:

  • Create an empty array and then fill it with a constant value using np.full for verification.
  • Contrast the behavior of np.empty and np.zeros by creating two arrays and comparing their initial values.
  • Generate an empty array using np.empty_like based on another array’s shape and then fill it with a designated number.
  • Write a function that outputs both an empty and a fully initialized array for a given shape and value.

Go to:


PREV : Append Values to Array
NEXT : Celsius to Fahrenheit Conversion


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.