Multiply a constant to all elements in array – NumPy

Numpy Array – Multiply a constant to all elements

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 *. Pass array and constant as operands to the multiplication operator as shown below.

output = arr * c

where

Examples

1. Multiply each of the element in the array with 3

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

Python Program

import numpy as np

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

# Print array
print("The array\n", arr)

# Multiplying a constant to all the elements of array
output = arr * 3

print("\nAfter multiplying a constant to all the elements of array\n", output)
Run Code

Output

Summary

In this NumPy Tutorial, we learned how to multiply a constant to each of the elements in array using multiplication operator.

Privacy Policy Terms of Use

SitemapContact Us