0
0
NumpyHow-ToBeginner ยท 3 min read

How to Add Arrays in NumPy: Simple Syntax and Examples

To add arrays in numpy, use the + operator or the numpy.add() function. Both methods perform element-wise addition of arrays with the same shape.
๐Ÿ“

Syntax

You can add arrays in NumPy using either the + operator or the numpy.add() function.

  • array1 + array2: Adds two arrays element-wise.
  • numpy.add(array1, array2): Does the same using a function call.

Both require arrays to have the same shape or be broadcastable.

python
import numpy as np

# Using + operator
result = np.array([1, 2, 3]) + np.array([4, 5, 6])

# Using numpy.add function
result_func = np.add(np.array([1, 2, 3]), np.array([4, 5, 6]))
๐Ÿ’ป

Example

This example shows how to add two arrays element-wise using both the + operator and the numpy.add() function.

python
import numpy as np

array1 = np.array([10, 20, 30])
array2 = np.array([1, 2, 3])

# Add arrays using + operator
sum_operator = array1 + array2

# Add arrays using numpy.add function
sum_function = np.add(array1, array2)

print("Sum using + operator:", sum_operator)
print("Sum using numpy.add():", sum_function)
Output
Sum using + operator: [11 22 33] Sum using numpy.add(): [11 22 33]
โš ๏ธ

Common Pitfalls

Common mistakes when adding arrays include:

  • Adding arrays of different shapes without compatible broadcasting, which causes errors.
  • Using Python lists instead of NumPy arrays, which does not perform element-wise addition.

Always ensure arrays have the same shape or compatible shapes for broadcasting.

python
import numpy as np

# Wrong: Adding arrays with incompatible shapes
try:
    a = np.array([1, 2, 3])
    b = np.array([4, 5])
    c = a + b
except ValueError as e:
    print("Error:", e)

# Wrong: Adding Python lists (concatenates instead of element-wise add)
list1 = [1, 2, 3]
list2 = [4, 5, 6]
print("List addition result:", list1 + list2)

# Right: Convert lists to arrays before adding
arr1 = np.array(list1)
arr2 = np.array(list2)
print("Array addition result:", arr1 + arr2)
Output
Error: operands could not be broadcast together with shapes (3,) (2,) List addition result: [1, 2, 3, 4, 5, 6] Array addition result: [5 7 9]
๐Ÿ“Š

Quick Reference

OperationSyntaxDescription
Add arrays element-wisearray1 + array2Adds two arrays element by element
Add arrays element-wise (function)numpy.add(array1, array2)Same as + operator but as a function
Broadcasting supportarray1 + array2 (different shapes)Adds arrays if shapes are compatible
Avoid adding Python listsUse numpy.array() firstLists concatenate instead of element-wise add
โœ…

Key Takeaways

Use the + operator or numpy.add() to add arrays element-wise in NumPy.
Arrays must have the same shape or compatible shapes for broadcasting.
Adding Python lists concatenates them; convert to NumPy arrays first.
Mismatched shapes without broadcasting cause errors.
numpy.add() is a function alternative to the + operator for addition.