Course Content

Ultimate NumPy

## Creation Functions for 1D Arrays

Besides basic array creation via explicitly specifying the elements of the array `numpy` also allows automatic array creation using special creation functions. Here are two of the most common creation functions which create exclusively 1D arrays:

• `arange()`;
• `linspace()`.

### arange()

`numpy.arange()` function is similar to the Python built-in `range()` function, however, it returns an `ndarray`. Basically, it creates an array with evenly spaced elements within a certain given interval.

### Start, Stop, Step

Its three most important parameters are `start` (`0` by default), `stop` (no default value) and `step` (`1` by default). The first array element is equal to `start`, and each next one is equal to the previous element + `step` until the `stop` value is reached (`stop` is not included in the array) or exceeded.

Let’s see this function in action:

For `array_1` we only set the `stop` parameter to `11`, for `array_2` we set both the `start` to `1` and `stop` to `11`, and for `array_3` we specified all of the three parameters with `step=2`.

As you can see with `array_4`, we can also specify the data type of the elements.

### linspace()

While `arange()` can work with real numbers, it is often better to use `numpy.linspace()` for this purpose. With `linspace()` instead of the `step` parameter there is `num` parameter used to specify the number of samples (numbers) within a given interval (50 by default).

Let’s see how we can use this function:

As you can see, everything is quite simple here.

### Endpoint

Let’s rather focus on the `endpoint` boolean parameter. Its default value is `True` meaning that the `stop` value is inclusive. Setting it to `False` excludes this value thus making the step lower and shifting the interval (have a closer look at `array_1` and `array_3`).

Note

You can always explore more about these functions in their documentation: arange, linspace.

1. Use the `arange()` function to create `even_numbers` array.
2. Specify the arguments in the correct order to create an array of even numbers from `2` to `21` exclusive.
3. Use the appropriate function to create `samples` array which allows specifying the number of values within an interval.
4. Specify the first three arguments in the correct order to create an array of `10` equally spaced numbers between `5` and `6`.
5. Set the rightmost keyword argument, so that `6` is not included in the `samples` array.