numpy.tril Method in Python

We can use the numpy.tril() method to get the lower triangle of an array. Its syntax is as follows

Syntax

numpy.tril(m, k=0)

where,

• m - number of rows in the array.

• k - It is the diagonal. Use k=0 for the main diagonal. k < 0 is below the main diagonal and k > 0 is above it.

It returns a copy of the array after replacing all the elements above the k thdiagonal with zero.

Example 1

Let us consider the following example −

# import numpy library
import numpy as np

# create an input matrix
x = np.matrix([[20, 21, 22], [44 ,45, 46], [78, 79, 80]])
print("Matrix Input :", x)

# numpy.tril() function
y = np.tril(x, -1)

# Display Tril Values
print("Tril Elements: ", y)

Output

It will generate the following output −

Matrix Input :
[[20 21 22]
[44 45 46]
[78 79 80]]
Tril Elements:
[[ 0 0 0]
[44 0 0]
[78 79 0]]

Example 2

Let us take another example −

# import numpy library
import numpy as np

# create an input matrix
a = np.matrix([[1, 2], [3, 4], [5, 6], [7, 8]])
print("Matrix Input :", a)

# numpy.tril() function
b = np.tril(a, -1)

# Display Tril Values
print("Tril Elements: ", b)

Output

It will generate the following output −

Matrix Input :
[[1 2]
[3 4]
[5 6]
[7 8]]
Tril Elements:
[[0 0]
[3 0]
[5 6]
[7 8]]