Home >Backend Development >Python Tutorial >How to create an array in Python?
Arrays in Python are ndarray objects. To create arrays in Python, use the Numpy library. An array is a container that can hold a fixed number of elements, and these elements should be of the same type. To use arrays in Python, import the NumPy library.
First, let’s install the Numpy library -
pip install numpy
Import the required Numpy libraries -
import numpy as np
Now let's create an array. Basic Numpy arrays are created using the array() function in NumPy -
import numpy as np # Create a Numpy Array arr = np.array([5, 10, 15, 20, 25]) print("Array = ",arr)
Array = [ 5 10 15 20 25]
We will create a two-dimensional array, a matrix. Here, a 2x3 matrix will be created -
import numpy as np # Create a Numpy Matrix 2x3 a = np.array([[5, 10, 15], [20, 25, 30]]) # Display the array with more than one dimension print("Array = ",a)
Array = [[ 5 10 15] [20 25 30]]
To get array dimensions in Python, use numpy.ndim. For a one-dimensional array, the dimension is 1.
Similarly, for a 2D array, the dimensions will be 2, etc. Now let's look at an example -
import numpy as np # Create a Numpy Matrix 2x3 arr = np.array([[5, 10, 15], [20, 25, 30]]) # Display the array with more than one dimension print("Array = \n",arr) print("Array Dimensions = ",arr.ndim)
Array = [[ 5 10 15] [20 25 30]] Array Dimensions = 2
The number of elements in each dimension of an array is called its shape. Use numpy.shape to get the array shape. Let's see an example of getting the shape of an array -
import numpy as np # Create a Numpy Matrix 2x3 arr = np.array([[5, 10, 15], [20, 25, 30]]) # Display the array print("Array = \n",arr) print("Array Shape = ",arr.shape)
Array = [[ 5 10 15] [20 25 30]] Array Shape = (2, 3)
We can easily initialize Numpy arrays with zeros -
import numpy as np # Create a Numpy Matrix 3x3 with zeros arr = np.zeros([3, 3]) # Display the array print("Array = \n",arr) print("Array Shape = ",arr.shape)
Array = [[0. 0. 0.] [0. 0. 0.] [0. 0. 0.]] Array Shape = (3, 3)
To sort an array in Numpy, use the sort() method -
import numpy as np # Create a Numpy Matrix arr = np.array([[5, 3, 8], [17, 25, 12]]) # Display the array print("Array = \n",arr) # Sort the array print("\nSorted array = \n", np.sort(arr))
Array = [[ 5 3 8] [17 25 12]] Sorted array = [[ 3 5 8] [12 17 25]]
The above is the detailed content of How to create an array in Python?. For more information, please follow other related articles on the PHP Chinese website!