![]() |
VOOZH | about |
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.
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:
The original list : [('gfg', 1, 9), ('is', 5, 10), (8, 'best', 13)]
Row of desired element is : 1Time Complexity: O(N) where N is the Number of rows
Auxiliary Space : O(1)
Method #3: Using the filter() function
Approach:
The original list : [('gfg', 1, 9), ('is', 5, 10), (8, 'best', 13)]
Row of desired element is : 1Time 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:
Below is the implementation of the above approach
The original list : [('gfg', 1, 9), ('is', 5, 10), (8, 'best', 13)]
Row of desired element is : 1Time 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:
The original list : [('gfg', 1, 9), ('is', 5, 10), (8, 'best', 13)]
Row of desired element is : 1Time 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.
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.