Python Numpy – Multiply a constant to all the elements of array

Numpy Array – Multiply a constant to all elements of the array

Multiplying a constant to a NumPy array is as easy as multiplying two numbers. To multiply a constant to each and every element of an array, use multiplication arithmetic operator *. To multiplication operator, pass array and constant as operands as shown below.

b = a * c
Run

where a is input array and c is a constant. b is the resultant array.

Example

In the following python example, we will multiply a constant 3 to an array a. The resulting array is stored in b.

import numpy as np

#2D array
a = (np.arange(8)*2).reshape(2,4)

#print array
print("The array\n",a)

#multiplying a constant to all the elements of array
b = a * 3

print("\nAfter multiplying a constant to all the elements of array\n",b)
Run
Python Numpy Array - Multiply constant