Add a Constant to all Elements of Array – NumPy

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

Adding a constant to a NumPy array is as easy as adding two numbers.

To add a constant to each and every element of an array, use addition arithmetic operator +. Pass array and constant as operands to the addition operator as shown below.

output = arr + c

where

  • arr is a numpy array.
  • c is a constant.
  • output is the resulting numpy array.

Examples

1. Add a constant of 3 to each element in the array

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

Python Program

import numpy as np

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

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

# Adding a constant to all the elemnets of array
output = arr + 3

print("\nAfter adding a constant to all the elemnets of array\n", output)
Run Code Copy

Output

Python Numpy Array - Add a constant

Summary

In this NumPy Tutorial, we learned how to add a constant to each of the element in numpy array using addition operator.

Code copied to clipboard successfully 👍