# np.tri: How to Use Numpy tri() Function in Python

Numpy tri() function creates an array with 1’s at and below the given diagonal(about k) and 0’s elsewhere. The tri() function is defined under numpy, which can be imported as import numpy as np. We can create multidimensional arrays and derive other mathematical statistics with the help of numpy, a library in Python.

## Numpy tri()

Numpy tri() function is used to create an array that contains 1’s at and below a given diagonal (k in this case) and 0’s at all other places of the array.

### Syntax

```numpy.tri(rows, columns, k, dtype)
```

### Parameters

The tri() function takes four parameters, out of which three parameters are optional.

The first parameter represents the number of rows; the second parameter is for the number of columns, and by default, it is equal to the number of rows.

The third parameter is the k, an integer value and 0 by default. If the value of k>0, it means diagonal is above the main diagonal and, if not vice versa, follows.

The fourth parameter is dtype, which is optional to mention by default. It takes float. (It is the data type of the returned array).

### Return Value

The tri() function returns an array with 1’s and 0’s values.

### Example programs on tri() method in Python

#### Write a program to show the working of the tri() function in Python.

```import numpy as np

print("tri with 3 rows 3 col and k=1 : \n", np.tri(3, 3, 1, dtype=float), "\n")
print("tri with 3 rows and 5 columns considering main diagonal : \n",
np.tri(3, 5, 0), "\n")
print("tri with 3 rows and 5 columns and k=-1: \n", np.tri(3, 5, -1), "\n")
```

#### Output

```tri with 3 rows 3 col and k=1 :
[[1. 1. 0.]
[1. 1. 1.]
[1. 1. 1.]]

tri with 3 rows and 5 columns considering main diagonal :
[[1. 0. 0. 0. 0.]
[1. 1. 0. 0. 0.]
[1. 1. 1. 0. 0.]]

tri with 3 rows and 5 columns and k=-1:
[[0. 0. 0. 0. 0.]
[1. 0. 0. 0. 0.]
[1. 1. 0. 0. 0.]]
```

In this example, we can see that we have taken different rows and columns, and we are getting 1s and 0s accordingly with the varying value of k, which is 1 for the 1st example, 0 for the second, and -1 for the third.

#### Write a program to take a 4×4 matrix and then apply the tri() function.

See the following code.

```import numpy as np

print("tri with 4 rows 4 col and k=1 : \n", np.tri(4, 4, 1, dtype=float), "\n")```

#### Output

```tri with 4 rows 4 col and k=1 :
[[1. 1. 0. 0.]
[1. 1. 1. 0.]
[1. 1. 1. 1.]
[1. 1. 1. 1.]]```

In this example, we can see that bypassing 4×4, we are getting a 4×4 array with zeros above the main diagonal because of the k value, which is passed equally to 1 over here.