Python: Two similar methods in Numpy to create array with initial content

Bruce Wen
2 min readOct 13, 2021

Numpy library provides several methods to create array with initial content. Two of them are to generate a sequence of values between start and end numbers: arange and linspace . What are difference between those two methods?

Photo by Kelly Sikkema on Unsplash

arange

>>> np.arange(0, 10)
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])

By given start and end numbers, it generates a sequence from start number to end number (not included) without interval (interval = 1) between numbers.

You can also specify interval:

>>> np.arange(0, 10, 3)
array([0, 3, 6, 9])

The interval could be float:

>>> np.arange(0, 10, 1.2)
array([0. , 1.2, 2.4, 3.6, 4.8, 6. , 7.2, 8.4, 9.6])

To generate 2-dimensional array, you need to combine arange with reshap :

>>> np.arange(0, 10, 1.2).reshape(3,3)
array([[0. , 1.2, 2.4],
[3.6, 4.8, 6. ],
[7.2, 8.4, 9.6]])

You have to make sure the size after reshape is correct, otherwise, it will fail:

>>> np.arange(0, 10, 1.2).reshape(3,4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: cannot reshape array of size 9 into shape (3,4)

linspace

You can use linspace to generate an array with 50 elements by default, from start number to end number:

>>> np.linspace(0, 10)
array([ 0. , 0.20408163, 0.40816327, 0.6122449 , 0.81632653,
1.02040816, 1.2244898 , 1.42857143, 1.63265306, 1.83673469,
2.04081633, 2.24489796, 2.44897959, 2.65306122, 2.85714286,
3.06122449, 3.26530612, 3.46938776, 3.67346939, 3.87755102,
4.08163265, 4.28571429, 4.48979592, 4.69387755, 4.89795918,
5.10204082, 5.30612245, 5.51020408, 5.71428571, 5.91836735,
6.12244898, 6.32653061, 6.53061224, 6.73469388, 6.93877551,
7.14285714, 7.34693878, 7.55102041, 7.75510204, 7.95918367,
8.16326531, 8.36734694, 8.57142857, 8.7755102 , 8.97959184,
9.18367347, 9.3877551 , 9.59183673, 9.79591837, 10. ])

The 3rd argument number is to tell how many elements will be generated from start number to end number, which is different from 3rd argument of arange method:

>>> np.linspace(0, 10, 3)
array([ 0., 5., 10.])

And as you see, the type of element is float by default. If you want to change, then passing dtype argument:

>>> np.linspace(0, 10, 3, dtype=int)
array([ 0, 5, 10])

Similarly, you can also combine with rshape to generate 2 dimensional array:

>>> np.linspace(0, 10, 6, dtype=int).reshape(2,3)
array([[ 0, 2, 4],
[ 6, 8, 10]])

Yes, that’s the simple introduction of two similar methods in numpy library to generate arrays with initial content between start and end number.

Thanks for reading and happy coding!

--

--