Python NumPy - Create an array of numbers 1 to N

By IncludeHelp Last updated : January 2, 2024

Problem statement

You have to create a NumPy array of numbers from 1 to N in Python.

Creating a NumPy array of numbers 1 to N

For this purpose, you can use numpy.arange() method which returns the numbers from the given start value to stop value within a given interval (step). The numpy.arange() method generally accepts 3 parameters start, stop, and step.

Below is the syntax of numpy.arange() method:

numpy.arange([start, ]stop, [step, ]dtype=None, *, like=None)

Let us understand with an example.

Python code to create a NumPy array of Numbers 1 to N

# Import NumPy module
import numpy as np

# Creating a NumPy array of numbers 1 to N
arr1 = np.arange(1, 100)

# Printing the type and value
print("arr1:\n", arr1)
print("Type of arr1:\n", type(arr1))

# Creating a NumPy array of numbers 1 to N
# with step 
arr2 = np.arange(1, 100, 3)

# Printing the type and value
print("arr2:\n", arr2)
print("Type of arr2:\n", type(arr2))

Output

The output of the above example is:

arr1:
 [ 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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
 97 98 99]
Type of arr1:
 <class 'numpy.ndarray'>
arr2:
 [ 1  4  7 10 13 16 19 22 25 28 31 34 37 40 43 46 49 52 55 58 61 64 67 70
 73 76 79 82 85 88 91 94 97]
Type of arr2:
 <class 'numpy.ndarray'>

Creating a NumPy array of float numbers

For this purpose, you can specify the dtype parameter as float in the numpy.arange() method, it will create an array of float numbers. You can also specify the steps.

Consider the below example:

# Import NumPy module
import numpy as np

# Creating a NumPy array of float numbers
arr = np.arange(1, 10, 0.5, dtype=float)

# Printing the type and value
print("arr:\n", arr)
print("Type of arr:\n", type(arr))

Output

The output of the above example is:

arr:
 [1.  1.5 2.  2.5 3.  3.5 4.  4.5 5.  5.5 6.  6.5 7.  7.5 8.  8.5 9.  9.5]
Type of arr:
 <class 'numpy.ndarray'>

To understand the above programs, you should have the basic knowledge of the following Python topics:

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.