In this tutorial, **you’ll learn how to use the NumPy linspace function to create arrays of evenly spaced numbers**. This can be incredibly helpful when you’re working with numerical applications. The NumPy linspace function allows you to create evenly spaced ranges of numbers and to customize these arrays using a wide assortment of parameters.

By the end of this tutorial, you’ll have learned:

- How to use the
`np.linspace()`

function to create evenly spaced arrays - How to tell
`np.linspace()`

apart from other, similar functions - How to understand the different parameters of the
`np.linspace()`

function - How to create arrays of two or more dimensions by passing in lists of values

Table of Contents

## Understanding the NumPy linspace() Function

Before diving into some practical examples, let’s take a look at the parameters that make up the `np.linspace()`

function. This will give you a good sense of what to expect in terms of its functionality.

```
# Understanding the np.linspace() Function
import numpy as np
np.linspace(
start,
stop,
num=50,
endpoint=True,
retstep=False,
dtype=None,
axis=0
)
```

Let’s take a closer look at the parameters. **The table below breaks down the parameters of the NumPy linspace() function, as well as its default and expected values:**

Parameter | Default Value | Data Type | Description |
---|---|---|---|

`start=` | N/A | Integer or array | The starting value of the sequence |

`stop=` | N/A | Integer or array | The end value of the sequence, unless `endpoint=` is set to `False` |

`num=` | `50` | Integer | The number of samples to generate. Must be non-negative. |

`endpoint=` | `True` | Boolean | Whether to use `stop` as the last sample |

`retstep=` | `False` | Boolean | If `True` , returns a tuple of `(samples, step)` , where the `step` is the spacing between samples |

`dtype=` | `None` | dtype | The data type of the output array. If `None` , the type will be inferred and will never be an integer. |

`axis=` | `0` | Integer | Relevant only if the `start` and `stop` parameters are array-like. Results in the axis in the result to store the samples. |

In the following section, we’ll dive into using the `np.linspace()`

function with some practical examples.

## Creating Evenly-Spaced Ranges of Numbers with NumPy linspace

The NumPy linspace function is useful for creating ranges of evenly-spaced numbers, without needing to define a step size. This can be very helpful when you want to have a define start and end point, as well as a given number of samples.

Let’s take a look at a simple example first, explore what it’s doing, and then build on top of it to explore the functionality of the function:

```
# Using the NumPy linspace() Function
import numpy as np
values = np.linspace(1, 50)
print(values)
# Returns:
# [ 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18.
# 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36.
# 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50.]
```

When can see from the code block above that when we passed in the values of `start=1`

and `end=50`

that we returned the values from 1 through 50. By default, the `np.linspace()`

function will return an array of 50 values.

The function, in this case, **returns a closed range linear space space of data type ndarray**. We say that the array is closed range because it includes the endpoint. In many other functions, such as the Python

`range()`

function, the endpoint isn’t included by default. ### Customizing the Step Size in NumPy linspace

Let’s see how we can use the `num=`

parameter to customize the number of values included in our linear space:

```
# Customizing the Number of Values in Our Array
import numpy as np
values = np.linspace(1, 50, num=10)
print(values)
# Returns:
# [ 1. 6.44444444 11.88888889 17.33333333 22.77777778 28.22222222
# 33.66666667 39.11111111 44.55555556 50. ]
```

We can see that this array returned 10 values, ranging from 0 through 50, which are evenly-spaced. The benefit of the linspace() function becomes clear here: we don’t need to define and understand the step size before creating our array.

### Customizing the Endpoint in NumPy linspace

By default, NumPy will include the `stop`

value specified in the function. This behavior is different from many other Python functions, including the Python `range()`

function. If we want to modify this behavior, then we can modify the `endpoint=`

parameter.

Let’s take a look at how this works:

```
# Modifying the Endpoint Behavior of the np.linspace() Function
import numpy as np
values = np.linspace(1, 50, endpoint=False)
print(values)
# Returns:
# [ 1. 1.98 2.96 3.94 4.92 5.9 6.88 7.86 8.84 9.82 10.8 11.78
# 12.76 13.74 14.72 15.7 16.68 17.66 18.64 19.62 20.6 21.58 22.56 23.54
# 24.52 25.5 26.48 27.46 28.44 29.42 30.4 31.38 32.36 33.34 34.32 35.3
# 36.28 37.26 38.24 39.22 40.2 41.18 42.16 43.14 44.12 45.1 46.08 47.06
# 48.04 49.02]
```

In the code block above, we modified our original example. In the previous case, the function returned values of step size `1`

. In the example above, we modified the behavior to exclude the endpoint of the values.

### Customizing the Data Type in NumPy linspace

By default, NumPy will infer the data type that is required. This occurs when the `dtype=`

parameter uses its default argument of `None`

. As we saw in our previous example, even when the numbers returned are evenly-spaced whole numbers, NumPy will never infer the data type to an integer.

Let’s see how we can replicate that example and explicitly force the values to be of an integer data type:

```
# Specifying the Data Type of Integer in the NumPy linspace() Function
import numpy as np
values = np.linspace(1, 50, dtype='int')
print(values)
# Returns:
# [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
# 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
# 49 50]
```

In the following section, you’ll learn how to extract the step size from the NumPy `linspace()`

function.

## Getting the Step Size from the NumPy linspace Function

In many other Python functions that return an array of values you need to define the step size. This makes the `np.linspace()`

function different, since you don’t need to define the step size. There may be times when you’re interested, however, in seeing what the step size is, you can modify the `retstep=`

parameter.

By modifying the `retstep=`

(“return step”) parameter to `True`

, the function will return a tuple that includes the range of values and the step size.

Let’s see how we can see how we can access the step size:

```
# Accessing the Step Size from the NumPy linspace() Function
import numpy as np
values = np.linspace(1, 10, num=15, retstep=True)
print(values)
# Returns:
# (array([ 1. , 1.64285714, 2.28571429, 2.92857143, 3.57142857,
# 4.21428571, 4.85714286, 5.5 , 6.14285714, 6.78571429,
# 7.42857143, 8.07142857, 8.71428571, 9.35714286, 10. ]), 0.6428571428571429)
```

We can unpack the values and the step size by unpacking the tuple directly when we declare the values:

```
# Unpacking the Array and Step Size from np.linspace()
import numpy as np
values, step_size = np.linspace(1, 10, num=15, retstep=True)
print(step_size)
# Returns: 0.6428571428571429
```

In the example above, we can see that we were able to see the step size. The benefit here is that we don’t need to define such a complex step size (or even really worry about what it is).

In the following section, you’ll learn how the `np.linspace()`

function compares to the `np.arange()`

function.

## NumPy linspace vs NumPy arange Functions

While both the `np.linspace()`

and `np.arange()`

functions return a range of values, they behave quite differently:

- The
`np.linspace()`

function returns a range of evenly-spaced values with a start, end, and number of values defined. In this case, the step size is up to the other parameters of the function. - The
`np.arange()`

function returns a range of evenly-spaced values with a start, end, and step size defined. In this case, the number of values is up to the other parameters of the function.

Based on that breakdown, we can see that while the functions are quite similar, they do have specific differences. The `np.linspace()`

function defines the number of values, while the `np.arange()`

function defines the step size.

## Creating Arrays of Two or More Dimensions with NumPy linspace

We can use the `np.linspace()`

function to create arrays of more than a single dimension. This can be helpful when we need to create data that is based on more than a single dimension.

Let’s take a look at an example and then how it works:

```
# Creating an Array of 2 Dimensions
import numpy as np
values = np.linspace([0,10], [10,100], num=5)
print(values)
# Returns:
# [[ 0. 10. ]
# [ 2.5 32.5]
# [ 5. 55. ]
# [ 7.5 77.5]
# [ 10. 100. ]]
```

Let’s break down what we did here:

- We defined starting points of
`[0,10]`

, meaning that the two arrays will start at 0 and 10, respectively - We then defined end points of
`[10, 100]`

, meaning that the arrays will end at 10 and 100, respectively - Both of these arrays have five numbers and they must be of the same length

We can also modify the axis of the resulting arrays. This can be helpful, depending on how you want your data generated. Let’s take a look:

```
# Modifying the Axis of Our Multi-Dimensional Array
import numpy as np
values = np.linspace([0,10], [10,100], num=5, axis=1)
print(values)
# Returns:
# [[ 0. 2.5 5. 7.5 10. ]
# [ 10. 32.5 55. 77.5 100. ]]
```

In the example above, we transposed the array by mapping it against the first axis.

## Using NumPy linspace to Plot Functions

The `np.linspace()`

function can be very helpful for plotting mathematical functions. Remember, the function returns a linear space, meaning that we can easily apply different functional transformations to data, using the arrays generated by the function.

Let’s see how we can plot the sigmoid function using the linear space of values between -100 and 100.

```
# Visualizing the Sigmoid Function in Python
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-100, 100)
y = 1.0 / (1.0 + np.exp(-x))
plt.plot(x, y)
plt.show()
```

This returns the following visualization:

As you can see, the lines are quite jagged. This is because, by default, NumPy will generate only fifty samples. Let’s increase this to 200 values and see if this changes the output:

```
# Adding More Values to an Array
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-100, 100, num=200)
y = 1.0 / (1.0 + np.exp(-x))
plt.plot(x, y)
plt.show()
```

This returns the following, smoothed image:

## Conclusions

In this tutorial, you learned how to use the NumPy linspace() function to create arrays of evenly-spaced values. You learned how to use the many different parameters of the function and what they do. Then, you learned how to use the function to create arrays of different sizes. You also learned how to access the step size of each value in the returned array. Finally, you learned how the function compares to similar functions and how to use the function in plotting mathematical functions.

## Additional Resources

To learn more about related topics, check out the tutorials below: