The NumPy var() function is used to compute the variance along the specified axis. The variance is a measure of the spread of a distribution. The variance is computed for the flattened array by default, otherwise over the specified axis.

### Syntax

```numpy.var(a, axis=None, dtype=None, out=None, keepdims=<no value>)
```

### Parameters

 `a` `Required. `Specify the input array. `axis` `Optional. `Specify axis or axes along which the variance is calculated. The default, axis=None, computes the variance of the flattened array.. `dtype` `Optional. `Specify the type to use in computing the variance. For arrays of integer type the default is float64, for arrays of float types it is the same as the array type. `out` `Optional. `Specify the output array in which to place the result. It must have the same shape as the expected output. `keepdims` `Optional. `If this is set to True, the reduced axes are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

### Return Value

Returns an array containing the variance if out=None, otherwise return a reference to the output array.

### Example: Variance of flattened array

In the below example, var() function is used to calculate variance of all values present in the array.

```import numpy as np
Arr = np.array([[1,2],[3, 4]])

print("Array is:")
print(Arr)

#variance of all values
print("\nVariance of all values:", np.var(Arr))
```

The output of the above code will be:

```Array is:
[[1 2]
[3 4]]

Variance of all values: 1.25
```

### Example: var() with axis parameter

When axis parameter is provided, variance is calculated over the specified axes as shown in the below example.

```import numpy as np
Arr = np.array([[10,20,30],[70,80,90]])

print("Array is:")
print(Arr)

#variance along axis=0
print("\nVariance along axis=0")
print(np.var(Arr, axis=0))

#variance along axis=1
print("\nVariance along axis=1")
print(np.var(Arr, axis=1))
```

The output of the above code will be:

```Array is:
[[10 20 30]
[70 80 90]]

Variance along axis=0
[900. 900. 900.]

Variance along axis=1
[66.66666667 66.66666667]
```

### Example: var() with dtype parameter

Computing the variance in float64 gives more accurate result. consider the following example.

```import numpy as np
Arr = np.array([1, 10, 100, 1000])

#variance using float32
print("Variance using float32:", np.var(Arr, dtype=np.float32))

#variance using float64
print("Variance using float64:", np.var(Arr, dtype=np.float64))
```

The output of the above code will be:

```Variance using float32: 175380.19
Variance using float64: 175380.1875
```

❮ NumPy - Functions

5