How to create a numeric sequence in Python using NumPy

In this article, let’s see how to create a numeric sequence in Python using NumPy. NumPy is a module that is commonly used for scientific, statistical analysis. NumPy arrays are grids of values of the same datatype. In this article, we will use NumPy arrays to generate a numeric sequence.

Installation of NumPy

If you don’t have NumPy already installed, a short description has been provided. If you have it installed already, skip this section and proceed further.

Open your command prompt and run the following command:

pip install numpy

To check if the installation was successful, run the following code in your Python shell.

import numpy

Running the above code should not produce any errors if the installation was done correctly. Let’s now jump right in!

How to create a numeric sequence in Python using NumPy

A numeric sequence is a series of values that follow a specific pattern. We will make use of a numpy array to store this series of values. We need to choose a generator to generate a numeric sequence and for this purpose, let’s choose the powers of 2 to be the numeric sequence. The newly generated values are appended to the end of the NumPy array. Let’s look at the code to implement this.

import numpy as np

def generate(value):
    return 2**value
arr = np.array([])

for value in range(0, 10):
    # Appends the new value to the end of the numpy array
    arr = np.append(arr, [generate(value)])
print(arr)

As the new values are generated, they are added to the end of the numpy array using the append function.

The output for the above code is as follows:

[  1.   2.   4.   8.  16.  32.  64. 128. 256. 512.]

Hence, we have generated a numeric sequence using NumPy arrays in Python. I hope you found this article helpful in understanding how to work with NumPy arrays.

See also:

Leave a Reply

Your email address will not be published. Required fields are marked *