Python Numpy – Create One Dimensional Array

Numpy – Create One Dimensional Array

One dimensional array contains elements only in one dimension. In other words, the shape of the numpy array should contain only one value in the tuple.

To create a one dimensional array in Numpy, you can use either of the array(), arange() or linspace() numpy functions.

Create 1D Numpy Array using array() function

Numpy array() functions takes a list of elements as argument and returns a one-dimensional array.

In this example, we will import numpy library and use array() function to crate a one dimensional numpy array.

Python Program

import numpy as np

#create numpy array
a = np.array([5, 8, 12])
print(a)
Run

Output

[ 5, 8, 12]

Create 1D Numpy Array using arange() function

Numpy arange() function takes start, end of a range and the interval as arguments and returns a one-dimensional array.

[start, start+interval, start+2*interval, ... ]
Run

In this example, we will import numpy library and use arange() function to crate a one dimensional numpy array.

Python Program

import numpy as np

#create numpy array
a = np.arange(5, 14, 2)
print(a)
Run

Output

[ 5, 7, 9, 11, 13]

Array starts with 5 and continues till 14 in the interval of 2.

Create 1D Numpy Array using linspace() function

Numpy linspace() functions takes start, end and the number of elements to be created as arguments and creates a one-dimensional array.

In this example, we will import numpy library and use linspace() function to crate a one dimensional numpy array.

Python Program

import numpy as np

#create numpy array
a = np.linspace(5, 25, 4)
print(a)
Run

Output

[ 5.         11.66666667 18.33333333 25.        ]

Summary

In this tutorial of Python Examples, we created one-dimensional numpy array using different built-in functions.