Get Nth Column of Matrix in Python

PythonServer Side ProgrammingProgramming

When it is required to get the ‘n’th column of a matrix, the ‘any’ method can be used.

Below is a demonstration of the same −

Example

 Live Demo

my_list = [[34, 67, 89], [16, 27, 86], [48, 30, 0]]

print("The list is : ")
print(my_list)

N = 1
print("The value of N has been initialized to -")
print(N)
elem = 30

my_result = any(sub[N] == elem for sub in my_list)

print("Does the element exist in a particular column ? ")
print(my_result)

Output

The list is :
[[34, 67, 89], [16, 27, 86], [48, 30, 0]]
The value of N has been initialized to -
1
Does the element exist in a particular column ?
True

Explanation

  • A list of list is defined, and is displayed on the console.

  • The value of N is initialized.

  • This is displayed on the console.

  • An elem variable is assigned an integer value.

  • The any method is used to see if any element in the list matches the elem variable previously defined.

  • The results are stored in a variable.

  • This is displayed as output on the console.

raja
Published on 16-Apr-2021 12:14:40
Advertisements