Python Program to find tuple indices from other tuple list
Last Updated :
30 Mar, 2023
Given Tuples list and search list consisting of tuples to search, our task is to write a Python Program to extract indices of matching tuples.
Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]
Output : [3, 1]
Explanation : (3, 4) from search list is found on 3rd index on test_list, hence included in result.
Input : test_list = [(4, 5), (7, 6), (1, 0), (3, 4)], search_tup = [(3, 4), (8, 9), (7, 6), (1, 0)]
Output : [3, 1, 2]
Explanation : (3, 4) from search list is found on 3rd index on test_list, hence included in result.
Method #1 : Using lookup dictionary + enumerate() + list comprehension
In this, a lookup dictionary is formed to map all the tuples with matching one's indices. Then lookup dictionary is used to get indices of mapped tuples as result using list comprehension.
step by step approach:
- Initialize a list of tuples named test_list containing some tuples.
- Print the original list of tuples using the print() function and str() function to convert the list into a string.
- Initialize another list of tuples named search_tup containing some tuples.
- Create a lookup dictionary named lookup_dict using a dictionary comprehension where the keys are the tuples in test_list and the values are their indices.
- Create a result list named res using a list comprehension that loops through each tuple idx in search_tup and checks if idx is present in the lookup_dict using the if idx in lookup_dict condition. If it is present, then the value of the corresponding key in the lookup_dict is appended to the res list.
- Print the resulting list of tuple indices using the print() function and str() function to convert the list into a string.
Python3
# Python3 code to demonstrate working of
# Find tuple indices from other tuple list
# Using lookup dictionary + enumerate() + list comprehension
# initializing list
test_list = [(4, 5), (7, 6), (1, 0), (3, 4)]
# printing original list
print("The original list is : " + str(test_list))
# initializing search tuple
search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]
# creating lookup_dict
lookup_dict = {val: key for key,val in enumerate(test_list)}
# creating result list
res = [lookup_dict[idx] for idx in search_tup if idx in lookup_dict]
# printing result
print("The match tuple indices : " + str(res))
Output:
The original list is : [(4, 5), (7, 6), (1, 0), (3, 4)]
The match tuple indices : [3, 1]
Time complexity: O(n) - where n is the length of the test_list or search_tup, whichever is larger. The creation of the lookup_dict has a time complexity of O(n), and the list comprehension has a time complexity of O(k) where k is the number of matches found in search_tup.
Auxiliary space: O(n) - where n is the length of the test_list. The lookup_dict takes up O(n) space.
Method #2 : Using list comprehension + enumerate()
In this, we perform the task of getting indices using enumerate(), and list comprehension is used for the task of iteration of all the elements of tuple and matching for equality.
Python3
# Python3 code to demonstrate working of
# Find tuple indices from other tuple list
# Using list comprehension + enumerate()
# initializing list
test_list = [(4, 5), (7, 6), (1, 0), (3, 4)]
# printing original list
print("The original list is : " + str(test_list))
# initializing search tuple
search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]
# enumerate() gets all the indices
res = [idx for idx, val in enumerate(test_list) for ele in search_tup if ele == val]
# printing result
print("The match tuple indices : " + str(res))
Output:
The original list is : [(4, 5), (7, 6), (1, 0), (3, 4)]
The match tuple indices : [1, 3]
Time Complexity: O(N)
Auxiliary Space: O(N)
Method #3 : Using index() method
Python3
# Python3 code to demonstrate working of
# Find tuple indices from other tuple list
# initializing list
test_list = [(4, 5), (7, 6), (1, 0), (3, 4)]
# printing original list
print("The original list is : " + str(test_list))
# initializing search tuple
search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]
res=[]
for i in search_tup:
if i in test_list:
res.append(test_list.index(i))
# printing result
print("The match tuple indices : " + str(res))
OutputThe original list is : [(4, 5), (7, 6), (1, 0), (3, 4)]
The match tuple indices : [3, 1]
Time Complexity: O(N)
Auxiliary Space: O(N)
Method #4: Using operator.countOf() method
Python3
# Python3 code to demonstrate working of
# Find tuple indices from other tuple list
import operator as op
# initializing list
test_list = [(4, 5), (7, 6), (1, 0), (3, 4)]
# printing original list
print("The original list is : " + str(test_list))
# initializing search tuple
search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]
res=[]
for i in search_tup:
if op.countOf(test_list,i)>0 :
res.append(test_list.index(i))
# printing result
print("The match tuple indices : " + str(res))
OutputThe original list is : [(4, 5), (7, 6), (1, 0), (3, 4)]
The match tuple indices : [3, 1]
Time Complexity: O(N)
Auxiliary Space: O(N)
Method 5: using the filter() function
Python3
# initializing list
test_list = [(4, 5), (7, 6), (1, 0), (3, 4)]
# printing original list
print("The original list is : " + str(test_list))
# initializing search tuple
search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]
res = list(filter(lambda x: test_list[x[0]] in search_tup, enumerate(test_list)))
res = [i for i, _ in res]
# printing result
print("The match tuple indices : " + str(res))
OutputThe original list is : [(4, 5), (7, 6), (1, 0), (3, 4)]
The match tuple indices : [1, 3]
Time complexity: O(n), where n is the length of the list test_list.
Auxiliary space: O(n) as well, since we are storing the indices of the matching tuples in the res list.
Method 6: Using the map function and a lambda function:
We can use the map function to apply a lambda function to each tuple in search_tup. The lambda function checks if the tuple exists in test_list using the in operator and returns the index using the index method if it does, and None otherwise. We then convert the map object to a list and filter out the None values using a list comprehension.
Python3
# initializing the list of tuples
test_list = [(4, 5), (7, 6), (1, 0), (3, 4)]
# initializing the search tuple
search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]
# using map function with lambda to find the indices of matching tuples
res = list(map(lambda x: test_list.index(
x) if x in test_list else None, search_tup))
# filtering out the None values and storing the result in a new list
res = [i for i in res if i is not None]
# printing the result
print("The match tuple indices : " + str(res))
OutputThe match tuple indices : [3, 1]
Time complexity: O(mn), where m is the length of search_tup and n is the length of test_list. .
Auxiliary space: O(m), where m is the length of search_tup.
Method 7: Using nested loops and tuple comparison.
Algorithm:
- Initialize an empty list res to store the indices of matching tuples.
- Iterate over each tuple tup in the search_tup list.
- Iterate over each tuple lst_tup in the test_list list.
- Check if tup is equal to lst_tup. If they are equal, append the index of lst_tup to res and break the inner loop.
- After both loops have completed, print the list of indices res.
Python3
test_list = [(4, 5), (7, 6), (1, 0), (3, 4)]
search_tup = [(3, 4), (8, 9), (7, 6), (1, 2)]
res = []
for i in range(len(search_tup)):
for j in range(len(test_list)):
if search_tup[i] == test_list[j]:
res.append(j)
break
print("The match tuple indices : " + str(res))
OutputThe match tuple indices : [3, 1]
Time Complexity:
The time complexity of this algorithm is O(N*M), where N is the length of the search_tup list and M is the length of the test_list list.
This is because we are iterating over each tuple in search_tup and checking it against each tuple in test_list.
In the worst-case scenario, where no tuples match, we will iterate over all N*M possible combinations of tuples.
However, in the best-case scenario, where the first tuple in search_tup matches the first tuple in test_list, we only need to iterate over one combination of tuples.
In general, the time complexity of this algorithm depends on the specific input data and the distribution of matching tuples between the two lists.
Space Complexity:
The space complexity of this algorithm is O(1), as we are only using a fixed amount of memory to store the variables res, i, j, tup, and lst_tup.
We do not create any new lists or dictionaries, so the space required by the algorithm does not depend on the size of the input data.
Similar Reads
Python Program to Convert Tuple Matrix to Tuple List Given a Tuple Matrix, flatten to tuple list with each tuple representing each column. Example: Input : test_list = [[(4, 5), (7, 8)], [(10, 13), (18, 17)]] Output : [(4, 7, 10, 18), (5, 8, 13, 17)] Explanation : All column number elements contained together. Input : test_list = [[(4, 5)], [(10, 13)]
8 min read
Python Program to Merge tuple list by overlapping mid tuple Given two lists that contain tuples as elements, the task is to write a Python program to accommodate tuples from the second list between consecutive tuples from the first list, after considering ranges present between both the consecutive tuples from the first list. Input : test_list1 = [(4, 8), (1
11 min read
Python List and Tuple Combination Programs Lists and tuples are two of the most commonly used data structures in Python. While lists are mutable and allow modifications, tuples are immutable and provide a stable structure for storing data. This article explores various programs related to list and tuple combinations, covering topics like:Sor
6 min read
Python | Find overlapping tuples from list Sometimes, while working with tuple data, we can have a problem in which we may need to get the tuples which overlap a certain tuple. This kind of problem can occur in Mathematics domain while working with Geometry. Let's discuss certain ways in which this problem can be solved. Method #1 : Using lo
5 min read
Python | Pair and combine nested list to tuple list Sometimes we need to convert between the data types, primarily due to the reason of feeding them to some function or output. This article solves a very particular problem of pairing like indices in list of lists and then construction of list of tuples of those pairs. Let's discuss how to achieve the
10 min read
Python - Ways to find indices of value in list In Python, it is common to locate the index of a particular value in a list. The built-in index() method can find the first occurrence of a value. However, there are scenarios where multiple occurrences of the value exist and we need to retrieve all the indices. Python offers various methods to achi
3 min read
Flatten tuple of List to tuple - Python The task of flattening a tuple of lists to a tuple in Python involves extracting and combining elements from multiple lists within a tuple into a single flattened tuple. For example, given tup = ([5, 6], [6, 7, 8, 9], [3]), the goal is to flatten it into (5, 6, 6, 7, 8, 9, 3). Using itertools.chain(
3 min read
Python - Find the Maximum of Similar Indices in two list of Tuples Sometimes, while working with Python records, we can have a problem in which we need to perform cross maximization of list of tuples. This kind of application is popular in web development domain. Letâs discuss certain ways in which this task can be performed. Method #1 : Using list comprehension +
7 min read
Python | Combining tuples in list of tuples Sometimes, we might have to perform certain problems related to tuples in which we need to segregate the tuple elements to combine with each element of complex tuple element( such as list ). This can have application in situations we need to combine values to form a whole. Let's discuss certain ways
7 min read