OKPEDIA PYTHON VECTOR

How to create an array of sequential numbers in Python

To initialize an array variable with a series of numbers in python, use the arange() function from the numpy library.

arange(start,end,step)

The parameters are integers

  • start The first number in the number series.
  • stop The final value of the series. It is not included in the series.
  • step The step between a number and the successor of the series. It is an optional parameter. If it is not indicated it is equal to +1 by default.

The arange () function creates a vector with n elements.

Examples

Example 1

Create a vector with the numbers 1 to 10.

>>> import numpy as np
>>> y=np.arange(1,10)

The arange function creates a vector of 10 elements.

>>> y
array([1, 2, 3, 4, 5, 6, 7, 8, 9])

Example 2

Create a vector of numbers from 1 to 10 using the step +2.

>>> import numpy as np
>>> y=np.arange(1,10,2)

The function creates a vector of 5 elements with a distance of 2 between the elements.

>>> y
array([1, 3, 5, 7, 9])

Example 3

Define a vector of a sequence of decreasing numbers from 10 to 1.

>>> import numpy as np
>>> y=np.arange(10,0,-1)

The content of the variable y is

>>> y
array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1])

The top of the range is not included in the vector.

https://how.okpedia.org/en/python/how-to-create-an-array-of-sequential-numbers-in-python


Report an error or share a suggestion to enhance this page


Python


FacebookTwitterLinkedinLinkedin