What is the numpy.tril() function in Python?

Overview

The tril() function in Python is used to return a lower triangle of an array.

Syntax

array.tril(m, k=0)

array is the name of the array to tril.

Parameters

The tril() function takes the following parameter values:

  • m: Represents the array_like object or the input array.
  • k: Represents the diagonal above or below the main diagonal. K<0 is below the main diagonal and k>0 is above the main diagonal.

Return value

The tril() function returns a lower triangle of the same shape and data type as the array m passed to it.

Example

import numpy as np
# creating an array
myarray = np.arange(9).reshape((3,3))
# implementing the tril() function
trilarray = np.tril(myarray, k=0)
print("Original array is:", myarray)
print("Manipulated array is:",trilarray)

Explanation

In the above code:

  • Line 1: We import the numpy library.
  • Line 4: We create an array myarray that contains 9 values with a dimension of 3 by 3 ( 3 rows and 3 columns) using the arange() function.
  • Line 7: We implement the tril() function on the array myarray using the main diagonal k = 0. The result is assigned to a new variable trilarray.
  • Line 9: We print the array myarray.
  • Line 10: We print the new array trilarray.

Free Resources