# Numpy Array Operations in Python

Numpy Array Operations: In this tutorial, we are going to learn about the various array operations using NumPy in Python programming language?
Submitted by Sapna Deraje Radhakrishna, on December 23, 2019

### Array with Array operations

```import numpy as np

arr = np.arange(0,11)
print(arr)

# returns the sum of the numbers
print(arr + arr)
# returns the diff between the numbers
print(arr - arr)
#  returns the multiplication of the numbers
print(arr * arr )
# the code will continue to run but shows an error
print(arr / arr )
```

Output

```[ 0  1  2  3  4  5  6  7  8  9 10]
[ 0  2  4  6  8 10 12 14 16 18 20]
[0 0 0 0 0 0 0 0 0 0 0]
[  0   1   4   9  16  25  36  49  64  81 100]
main.py:13: RuntimeWarning: invalid value encountered in true_divide
print(arr / arr )
[nan  1.  1.  1.  1.  1.  1.  1.  1.  1.  1.]
```

### Array with Scalar operations

Similar to array with array operations, a NumPy array can be operated with any scalar numbers. Below are few examples,

```import numpy as np

arr = np.arange(0,11)
print(arr)

print(arr ** 2)
print(arr + 1)
print(arr - 2)
print(arr *100)
print(arr /100)
```

Output

```[ 0  1  2  3  4  5  6  7  8  9 10]
[  0   1   4   9  16  25  36  49  64  81 100]
[ 1  2  3  4  5  6  7  8  9 10 11]
[-2 -1  0  1  2  3  4  5  6  7  8]
[   0  100  200  300  400  500  600  700  800  900 1000]
[0.   0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 0.09 0.1 ]
```

### Universal Array Functions

NumPy supports universal array functions which are essentially just mathematical functions used to perform the operation and broadcast across the entire array.

Some of the common examples are,

```import numpy as np

arr = np.arange(0,11)
print(arr)

# will return the square root of all elements
print(np.sqrt(arr))
# will return the exponential of all elements
print(np.exp(arr))
# will return the max value
print(np.max(arr))
# will return sin value
print(np.sin(arr))
# will return log value. If error, issue warnings
print(np.log(arr))
#will return cos value
print(np.cos(arr))
```

Output

```[ 0  1  2  3  4  5  6  7  8  9 10]
[0.         1.         1.41421356 1.73205081 2.         2.23606798 2.44948974 2.64575131 2.82842712 3.         3.16227766]
[1.00000000e+00 2.71828183e+00 7.38905610e+00 2.00855369e+01
5.45981500e+01 1.48413159e+02 4.03428793e+02 1.09663316e+03 2.98095799e+03 8.10308393e+03 2.20264658e+04]
10[ 0.          0.84147098  0.90929743  0.14112001 -0.7568025  -0.95892427
-0.2794155   0.6569866   0.98935825  0.41211849 -0.54402111]
main.py:15: RuntimeWarning: divide by zero encountered in log
print(np.log(arr))[      -inf 0.         0.69314718 1.09861229 1.38629436 1.60943791
1.79175947 1.94591015 2.07944154 2.19722458 2.30258509][ 1.          0.54030231 -0.41614684 -0.9899925  -0.65364362  0.28366219
0.96017029  0.75390225 -0.14550003 -0.91113026 -0.83907153]
```

Refer to link https://docs.scipy.org/doc/numpy/reference/ufuncs.html for the list of operations provided by NumPy.

Preparation