Open In App

Python | Search in Nth column in list of tuples

Last Updated : 26 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Initiated a for loop over the list of tuples.
  2. Check for an element in the Nth column of every row
  3. 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))


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 Number of rows
Auxiliary Space : O(1)

Method #3: Using the filter() function

Approach:

  1. Create a list of tuples named test_list containing some values. Each tuple in the list has three values.
  2. Print the original list test_list.
  3. Initialize N to 2, which represents the index of the column that we want to search for an element in.
  4. Initialize ele to 10, which is the element that we want to find in the Nth column.
  5. 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.
  6. Convert the filtered result to a list and get the index of the first element using the index() method.
  7. Print the index of the first tuple in the filtered list that has ele in the Nth column.
  8. 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.")


Output

The 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)


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 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)


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 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))


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 input list. 
Auxiliary space: O(1), as we are not creating any new lists or data structures.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads