numpy.empty() in Python

The numpy module of Python provides a function called numpy.empty(). This function is used to create an array without initializing the entries of given shape and type.

Just like numpy.zeros(), the numpy.empty() function doesn't set the array values to zero, and it is quite faster than the numpy.zeros(). This function requires the user to set all the values in the array manually and should be used with caution.

Syntax

snippet
numpy.empty(shape, dtype=float, order='C')

Parameters:

shape: int or tuple of ints

This parameter defines the shape of the empty array, such as (3, 2) or (3, 3).

dtype: data-type(optional)

This parameter defines the data type, which is desired for the output array.

order: {'C', 'F'}(optional)

This parameter defines the order in which the multi-dimensional array is going to be stored either in row-major or column-major. By default, the order parameter is set to 'C'.

Returns:

This function returns the array of uninitialized data that have the shape, dtype, and order defined in the function.

Example 1:

snippet
import numpy as np
x = np.empty([3, 2])
x

Output:

Output
array([[7.56544226e-316, 2.07617768e-316], [2.02322570e-316, 1.93432036e-316], [1.93431918e-316, 1.93431799e-316]])

In the above code

  • We have imported numpy with alias name np.
  • We have declared the variable 'x' and assigned the returned value of the np.empty() function.
  • We have passed the shape in the function.
  • Lastly, we tried to print the value of 'x' and the difference between elements.

Example 2:

snippet
import numpy as np
x = np.empty([3, 3], dtype=float)
x

Output:

Output
array([[ 2.94197848e+120, -2.70534020e+252, -4.25371363e+003], [ 1.44429964e-088, 3.12897830e-053, 1.11313317e+253], [-2.28920735e+294, -5.11507284e+039, 0.00000000e+000]])

Example 3:

snippet
import numpy as np
x = np.empty([3, 3], dtype=float, order='C')
x

Output:

Output
array([[ 2.94197848e+120, -2.70534020e+252, -4.25371363e+003], [ 1.44429964e-088, 3.12897830e-053, 1.11313317e+253], [-2.28920735e+294, -5.11507284e+039, 0.00000000e+000]])

In the above code

  • We have imported numpy with alias name np.
  • We have declared the variable 'x' and assigned the returned value of the np.empty() function.
  • We have passed the shape, data-type, and order in the function.
  • Lastly, we tried to print the value of 'x' and the difference between elements.

In the output, it shows an array of uninitialized values of defined shape, data type, and order.

Example 4:

snippet
import numpy as np
x = np.empty([3, 3], dtype=float, order='F')
x

Output:

Output
array([[ 2.94197848e+120, 1.44429964e-088, -2.28920735e+294], [-2.70534020e+252, 3.12897830e-053, -5.11507284e+039], [-4.25371363e+003, 1.11313317e+253, 0.00000000e+000]])
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +