Python | Search in Nth column in list of tuples
Last Updated :
26 Apr, 2023
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.
Method #1: Using enumerate() + list comprehension
In this technique, we use the power of enumerate() to access index and value in a single iteration, and then with the help of list comprehension, we frame a conditional statement in which we check for the valid value in the given column.
Python3
# Python3 code to demonstrate working of
# Search in Nth column in list of tuples
# Using enumerate() + list comprehension
# initializing list
test_list = [('gfg', 1, 9), ('is', 5, 10), (8, 'best', 13)]
# printing list
print("The original list : " + str(test_list))
# initializing Nth column
N = 2
# initializing num
ele = 10
# Search in Nth column in list of tuples
# Using enumerate() + list comprehension
res = [idx for idx, val in enumerate(test_list) if val[N] == ele]
# Printing result
print("Row of desired element is : " + str(res))
Output :
The original list : [('gfg', 1, 9), ('is', 5, 10), (8, 'best', 13)]
Row of desired element is : [1]
Time Complexity: O(n), where n is the length of the list test_list
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Method #2: Using for loop
Approach:
- Initiated a for loop over the list of tuples.
- Check for an element in the Nth column of every row
- If found display that row index.
Python3
# Python3 code to demonstrate working of
# Search in Nth column in list of tuples
# initializing list
test_list = [('gfg', 1, 9), ('is', 5, 10), (8, 'best', 13)]
# printing list
print("The original list : " + str(test_list))
# initializing Nth column
N = 2
# initializing num
ele = 10
# Search in Nth column in list of tuples
res = 0
for i in range(0, len(test_list)):
if ele == test_list[i][N]:
res = i
# Printing result
print("Row of desired element is : " + str(res))
OutputThe original list : [('gfg', 1, 9), ('is', 5, 10), (8, 'best', 13)]
Row of desired element is : 1
Time Complexity: O(N) where N is the Number of rows
Auxiliary Space : O(1)
Method #3: Using the filter() function
Approach:
- Create a list of tuples named test_list containing some values. Each tuple in the list has three values.
- Print the original list test_list.
- Initialize N to 2, which represents the index of the column that we want to search for an element in.
- Initialize ele to 10, which is the element that we want to find in the Nth column.
- Use the filter() function to filter the tuples in test_list that have ele in the Nth column. The lambda function is used to define the filtering condition.
- Convert the filtered result to a list and get the index of the first element using the index() method.
- Print the index of the first tuple in the filtered list that has ele in the Nth column.
- If the filtered list is empty, handle the IndexError exception and print a message indicating that the desired element was not found in the Nth column.
Python3
# initializing list
test_list = [('gfg', 1, 9), ('is', 5, 10), (8, 'best', 13)]
# printing list
print("The original list : " + str(test_list))
# initializing Nth column
N = 2
# initializing num
ele = 10
# Search in Nth column in list of tuples using filter()
filtered_list = filter(lambda x: x[N] == ele, test_list)
try:
res = test_list.index(list(filtered_list)[0])
# Printing desired elements in a row
print("Row of desired element is : " + str(res))
except IndexError:
# Display message for indentError
print("Desired element not found in Nth column.")
OutputThe original list : [('gfg', 1, 9), ('is', 5, 10), (8, 'best', 13)]
Row of desired element is : 1
Time complexity: O(n)
Auxiliary space: O(n), where n is the number of tuples in the list.
Method #4: using the index() method
Step-by-step approach:
- Initialize the list of tuples.
- Print the original list.
- Initialize the Nth column and the desired element.
- Find the index of the tuple containing the desired element using the index() method.
- Print the index of the tuple containing the desired element.
Below is the implementation of the above approach
Python3
# Python3 code to demonstrate working of
# Search in Nth column in list of tuples
# initializing list
test_list = [('gfg', 1, 9), ('is', 5, 10), (8, 'best', 13)]
# printing list
print("The original list : ", test_list)
# initializing Nth column
N = 2
# initializing num
ele = 10
# Search in Nth column in list of tuples
try:
res = test_list.index([t for t in test_list if t[N] == ele][0])
except IndexError:
res = -1
# Printing result
print("Row of desired element is : ", res)
OutputThe original list : [('gfg', 1, 9), ('is', 5, 10), (8, 'best', 13)]
Row of desired element is : 1
Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(1), as we only use a constant amount of additional memory to store the Nth column and the desired element.
Method #5: Using a generator expression inside the index() method.
steps to implement this approach:
- Initialize the list of tuples.
- Initialize the index of the column to be searched and the value to be searched.
- Use the index() method with a generator expression to search for the value in the specified column of the list of tuples.
- Assign the index to a variable if the value is found, otherwise assign -1 to the variable.
- Print the result.
Python3
# initializing list
test_list = [('gfg', 1, 9), ('is', 5, 10), (8, 'best', 13)]
# printing list
print("The original list : ", test_list)
# initializing Nth column and num
N = 2
ele = 10
# Search in Nth column in list of tuples using index() method with generator expression
try:
res = next(i for i, tup in enumerate(test_list) if tup[N] == ele)
except StopIteration:
res = -1
# Printing result
print("Row of desired element is : ", res)
OutputThe original list : [('gfg', 1, 9), ('is', 5, 10), (8, 'best', 13)]
Row of desired element is : 1
Time complexity: O(n), where n is the number of tuples in the list.
Auxiliary space: O(1) as we are only storing the index in a variable.
Method 6: Using a lambda function and map() function
Use the enumerate() function to add an index to each tuple in the list. We then use the filter() function with a lambda function to select only those tuples where the Nth column has the desired value. Finally, we use the map() function with another lambda function to extract only the index from each tuple that satisfies the condition. The list() function is used to convert the resulting map object into a list.
Python3
# Python3 code to demonstrate working of
# Search in Nth column in list of tuples
# Using lambda function and map() function
# initializing list
test_list = [('gfg', 1, 9), ('is', 5, 10), (8, 'best', 13)]
# printing list
print("The original list : " + str(test_list))
# initializing Nth column
N = 2
# initializing num
ele = 10
# Search in Nth column in list of tuples
# Using lambda function and map() function
res = list(map(lambda x: x[0], filter(
lambda x: x[1][N] == ele, enumerate(test_list))))
# Printing result
print("Row of desired element is : " + str(res))
OutputThe original list : [('gfg', 1, 9), ('is', 5, 10), (8, 'best', 13)]
Row of desired element is : [1]
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(1), as we are not creating any new lists or data structures.
Similar Reads
Python | Search in Nth Column of Matrix
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. Met
10 min read
Custom Sorting in List of Tuples - Python
The task of custom sorting in a list of tuples often involves sorting based on multiple criteria. A common example is sorting by the first element in descending order and the second element in ascending order. For example, given a = [(7, 8), (5, 6), (7, 5), (10, 4), (10, 1)], sorting the tuples by t
3 min read
Python | Summation of Kth Column of Tuple List
Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the possible accumulation of its Kth index. This problem has applications in the web development domain while working with data information. Let's discuss certain ways in which this task ca
7 min read
Python - Column Minimum in Tuple list
Sometimes, while working with records, we can have a problem in which we need to find min of all the columns of a container of lists which are tuples. This kind of application is common in web development domain. Letâs discuss certain ways in which this task can be performed. Method #1 : Using min()
6 min read
Python - Get maximum of Nth column from tuple list
Sometimes, while working with Python lists, we can have a task in which we need to work with tuple list and get the maximum of its Nth index. This problem has application in web development domain while working with data information. Letâs discuss certain ways in which this task can be performed. Me
7 min read
Python - Multiple Column Sort in Tuples
Sometimes, while working with records, we can have a problem in which we need to perform sort operation on one of the columns, and on other column, if equal elements, opposite sort. This kind of problem can occur as application in many domains such as web development. Lets discuss certain ways in wh
4 min read
Python - Kth Column Product in Tuple List
Sometimes, while working with Python list, we can have a task in which we need to work with tuple list and get the product of itâs Kth index. This problem has application in web development domain while working with data informations. Letâs discuss certain ways in which this task can be performed. M
7 min read
Python | Convert list of tuples into list
In Python we often need to convert a list of tuples into a flat list, especially when we work with datasets or nested structures. In this article, we will explore various methods to Convert a list of tuples into a list. Using itertools.chain() itertools.chain() is the most efficient way to flatten a
3 min read
Convert list of strings to list of tuples in Python
Sometimes we deal with different types of data types and we require to inter-convert from one data type to another hence interconversion is always a useful tool to have knowledge. This article deals with the converse case. Let's discuss certain ways in which this can be done in Python. Method 1: Con
5 min read
Python | Convert list of tuples into digits
Given a list of tuples, the task is to convert it into list of all digits which exists in elements of list. Letâs discuss certain ways in which this task is performed. Method #1: Using re The most concise and readable way to convert list of tuple into list of all digits which exists in elements of l
6 min read