Python | Search in Nth Column of Matrix
Last Updated :
21 Apr, 2023
Sometimes, while working with Python Matrix, we can have a problem in which we need to check if an element is present or not. This problem is simpler, but a variation to it can be to perform a check in a particular column of Matrix. Let’s discuss a shorthand by which this task can be performed.
Method 1: Using any() + list comprehension
This task can be performed using a combination of the above functions in which we imply list comprehension for iteration and support tasks and any() can be used to check for any occurrence of the desired character.
Step-by-step approach ;
- Initialize a list of lists test_list containing three sub-lists, each containing three integer values.
- Print the original list test_list using the print() function along with a string message.
- Initialize a variable N with the value 1, indicating the index of the column in which we want to search for the element.
- Initialize a variable ele with the value 3, indicating the element we want to search for in the specified column.
- Use the any() function along with a list comprehension to check if the element ele exists in the Nth column of the matrix test_list. The list comprehension iterates through each sublist of test_list and checks if the element at index N of the sublist is equal to ele. The any() function returns True if any element in the list comprehension is True, indicating that the element ele exists in the specified column.
- Store the result of the search in the variable res.
- Print the result of the search using the print() function along with a string message.
Below is the implementation of the above approach:
Python3
test_list = [[ 1 , 4 , 5 ], [ 6 , 7 , 8 ], [ 8 , 3 , 0 ]]
print ( "The original list : " + str (test_list))
N = 1
ele = 3
res = any (sub[N] = = ele for sub in test_list)
print ( "Does element exists in particular column : " + str (res))
|
Output
The original list : [[1, 4, 5], [6, 7, 8], [8, 3, 0]]
Does element exists in particular column : True
Time complexity: O(n), where n is the total number of elements in the matrix because we have to iterate through all the elements of the matrix to check if the element exists in the particular column.
Auxiliary space: O(1), because only a few variables are used and the memory usage does not depend on the size of the input.
Method 2: Using map() and lambda function:
Using the map() function along with a lambda function allows you to apply a specific operation to each element in an iterable such as a list or matrix. In this case, you can use the lambda function to check the Nth element of each row and return a list of boolean values indicating whether the element was present in that row or not. The map() function will apply the lambda function to each element in the matrix (rows), so the time complexity of this approach would be O(n) where n is the number of rows in the matrix. And Auxiliary space of this approach would be O(n) as well, as it creates a new list of booleans for each element in the matrix.
Here is an example of how to use the map() function along with a lambda function to check if an element is present in a particular column of a matrix:
Python3
test_list = [[ 1 , 4 , 5 ], [ 6 , 7 , 8 ], [ 8 , 3 , 0 ]]
print ( "The original list : " + str (test_list))
N = 1
ele = 3
res = True in list ( map ( lambda x: x[N] = = ele, test_list))
print ( "Does element exists in particular column : " + str (res))
|
Output
The original list : [[1, 4, 5], [6, 7, 8], [8, 3, 0]]
Does element exists in particular column : True
Time complexity: O(n), where n is the number of rows in the matrix (list of lists).
Auxiliary space: O(1), as it only uses a few constant-size variables (N, ele, res) and does not create any additional data structures.
Method 3: Using a for loop to iterate over each row and then accessing the element at the Nth column, comparing it with the desired element and setting a flag if found.
This program searches for a specific element in a particular column of a matrix represented as a list of lists. It initializes the matrix, the column to search (N), and the element to find (ele). It then uses a for loop to iterate through each row of the matrix and checks if the element exists in the Nth column of that row. If the element is found in the specified column, it sets the variable “found” to True and breaks out of the loop. Finally, it prints whether the element exists in the particular column or not.
Python3
test_list = [[ 1 , 4 , 5 ], [ 6 , 7 , 8 ], [ 8 , 3 , 0 ]]
print ( "The original list : " + str (test_list))
N = 1
ele = 3
found = False
for row in test_list:
if row[N] = = ele:
found = True
break
print ( "Does element exists in particular column : " + str (found))
|
Output
The original list : [[1, 4, 5], [6, 7, 8], [8, 3, 0]]
Does element exists in particular column : True
The time complexity of this method is O(n), where n is the number of rows in the matrix
The space complexity of this method is O(1), as we only use a constant amount of extra space to store the variables N, ele, and found.
Method 4: numpy library
step-by-step approach:
- Import the numpy library
- Initialize the list as a numpy array
- Initialize the Nth column index and the desired element
- Use numpy.any() function to check if the desired element exists in the Nth column
- Print the result
Python3
import numpy as np
test_list = np.array([[ 1 , 4 , 5 ], [ 6 , 7 , 8 ], [ 8 , 3 , 0 ]])
print ( "The original list : " )
print (test_list)
N = 1
ele = 3
found = np. any (test_list[:, N] = = ele)
print ( "Does element exists in particular column : " + str (found))
|
Output:
The original list :
[[1 4 5]
[6 7 8]
[8 3 0]]
Does element exists in particular column : True
Time complexity: O(n), where n is the number of elements in the matrix.
Auxiliary space: O(1)
Method 5: Using pandas library.
Step-by-step approach:
- Import pandas library.
- Create a DataFrame using the numpy array.
- Use the ‘iloc’ function to extract the Nth column.
- Use the ‘any’ function to check if the element exists in the extracted column.
- Print the result.
Python3
import numpy as np
import pandas as pd
test_list = np.array([[ 1 , 4 , 5 ], [ 6 , 7 , 8 ], [ 8 , 3 , 0 ]])
df = pd.DataFrame(test_list)
N = 1
ele = 3
found = df.iloc[:, N].isin([ele]). any ()
print ( "Does element exists in particular column : " + str (found))
|
Output:
Does element exists in particular column : True
Time complexity: O(m*n), where m is the number of rows and n is the number of columns in the matrix.
Auxiliary space: O(m*n), as we create a DataFrame to store the matrix.
Method 6: Using the in-built function index()
Step-by-step approach:
- Initialize a 2D list of integers called test_list with three sublists of three integers each.
- Print the original list using print() and str().
- Initialize an integer variable N to 1. This variable represents the column we want to check for the presence of ele.
- Initialize an integer variable ele to 3. This is the element we want to check for in the column.
- Set a boolean variable res to False. This variable will store the result of whether the element exists in the column.
- Use a for loop to iterate through each sublist in test_list.
- Within the loop, use a try-except block to catch a ValueError if ele is not found in the current sublist.
- If ele is found in the current sublist, use the index() function to get the index of ele in the sublist.
- If the index of ele in the sublist equals N, set res to True and break out of the loop.
- If ele is not found in the current sublist, continue to the next sublist in the loop.
- After the loop finishes, print the result using print() and str().
Below is the implementation of the above approach:
Python3
test_list = [[ 1 , 4 , 5 ], [ 6 , 7 , 8 ], [ 8 , 3 , 0 ]]
print ( "The original list : " + str (test_list))
N = 1
ele = 3
res = False
for lst in test_list:
try :
idx = lst.index(ele)
if idx = = N:
res = True
break
except ValueError:
pass
print ( "Does element exists in particular column : " + str (res))
|
Output
The original list : [[1, 4, 5], [6, 7, 8], [8, 3, 0]]
Does element exists in particular column : True
Time complexity: O(n*m) where n is the number of rows and m is the number of columns in test_list.
Auxiliary space: O(1) because it uses a constant amount of memory regardless of the size of test_list
Method 7: Using itertools:
- Import the itertools module
- Initialize the original list
- Initialize the column index (N) and the element to search (ele)
- Use itertools.chain() to flatten the nested list into a single list
- Use any() to check if the element exists in the Nth position of the flattened list
- Return the boolean result
Python3
import itertools
test_list = [[ 1 , 4 , 5 ], [ 6 , 7 , 8 ], [ 8 , 3 , 0 ]]
print ( "The original list : " + str (test_list))
N = 1
ele = 3
flat_list = list (itertools.chain( * test_list))
res = any (flat_list[i] = = ele for i in range (N, len (flat_list), len (test_list)))
print ( "Does element exists in particular column : " + str (res))
|
Output
The original list : [[1, 4, 5], [6, 7, 8], [8, 3, 0]]
Does element exists in particular column : True
Time complexity: O(n^2) where n is the number of elements in the matrix. This is because itertools.chain() requires iterating over the entire matrix and then flattening it, and any() also requires iterating over the entire flattened list.
Space complexity: O(n) for the flattened list, since it requires creating a new list that contains all the elements of the matrix.
Similar Reads
Python | Search in Nth column in list of tuples
Sometimes, while working with Python list, we can have a data set that consists of tuples and we have a problem in which we need to search the element in the Nth column of list. This has it's applications in web development domain. Let's discuss certain ways in which this task can be performed. Meth
7 min read
Search Elements in a Matrix - Python
The task of searching for elements in a matrix in Python involves checking if a specific value exists within a 2D list or array. The goal is to efficiently determine whether the desired element is present in any row or column of the matrix. For example, given a matrix a = [[4, 5, 6], [10, 2, 13], [1
3 min read
Python - Rear column in Multi-sized Matrix
Given a Matrix with variable lengths rows, extract last column. Input : test_list = [[3, 4, 5], [7], [8, 4, 6], [10, 3]] Output : [5, 7, 6, 3] Explanation : Last elements of rows filtered. Input : test_list = [[3, 4, 5], [7], [8, 4, 6]] Output : [5, 7, 6] Explanation : Last elements of rows filtered
4 min read
Python | Nth column Matrix Product
Sometimes, while working with Python Matrix, we may have a problem in which we require to find the product of a particular column. This can have a possible application in day-day programming and competitive programming. Letâs discuss certain ways in which this task can be performed. Method #1: Using
7 min read
Python - Summation of kth column in a matrix
Sometimes, while working with Python Matrix, we may have a problem in which we require to find the summation of a particular column. This can have a possible application in day-day programming and competitive programming. Letâs discuss certain ways in which this task can be performed. Method #1 : Us
8 min read
Python | Get Kth Column of Matrix
Sometimes, while working with Python Matrix, one can have a problem in which one needs to find the Kth column of Matrix. This is a very popular problem in Machine Learning Domain and having solution to this is useful. Let's discuss certain ways in which this problem can be solved. Method #1 : Using
6 min read
Summation Matrix columns - Python
The task of summing the columns of a matrix in Python involves calculating the sum of each column in a 2D list or array. For example, given the matrix a = [[3, 7, 6], [1, 3, 5], [9, 3, 2]], the goal is to compute the sum of each column, resulting in [13, 13, 13]. Using numpy.sum()numpy.sum() is a hi
2 min read
Linear Search - Python
Given an array, arr of n elements, and an element x, find whether element x is present in the array. Return the index of the first occurrence of x in the array, or -1 if it doesnât exist. Examples: Input: arr[] = [10, 50, 30, 70, 80, 20, 90, 40], x = 30Output : 2Explanation: For array [10, 50, 30, 7
4 min read
Take Matrix input from user in Python
Matrix is nothing but a rectangular arrangement of data or numbers. In other words, it is a rectangular array of data or numbers. The horizontal entries in a matrix are called as 'rows' while the vertical entries are called as 'columns'. If a matrix has r number of rows and c number of columns then
5 min read
Python - Custom Columns Matrix
Sometimes, while working with Python lists, we can have a problem in which we need to extract certain columns from Matrix and recreate it. This kind of problem can have applications in data domains as they use Matrix as a prominent input parameter. Let's discuss certain ways in which this task can b
5 min read