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:
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
0 by default),
stop (no default value) and
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:
array_1 we only set the
stop parameter to
array_2 we set both the
11, and for
array_3 we specified all of the three parameters with
As you can see with
array_4, we can also specify the data type of the elements.
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.
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
- Use the
arange()function to create
- Specify the arguments in the correct order to create an array of even numbers from
- Use the appropriate function to create
samplesarray which allows specifying the number of values within an interval.
- Specify the first three arguments in the correct order to create an array of
10equally spaced numbers between
- Set the rightmost keyword argument, so that
6is not included in the
Everything was clear?