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 unique keys count for Value in Tuple List
Given dual tuples, get a count of unique keys for each value present in the tuple. Input : test_list = [(3, 4), (1, 2), (2, 4), (8, 2), (7, 2), (8, 1), (9, 1), (8, 4), (10, 4)] Output : {4: 4, 2: 3, 1: 2} Explanation : 3, 2, 8 and 10 are keys for value 4. Input : test_list = [(3, 4), (1, 2), (8, 1),
6 min read
Python program to Flatten Nested List to Tuple List
Given a list of tuples with each tuple wrapped around multiple lists, our task is to write a Python program to flatten the container to a list of tuples. Input : test_list = [[[(4, 6)]], [[[(7, 4)]]], [[[[(10, 3)]]]]]Output : [(4, 6), (7, 4), (10, 3)]Explanation : The surrounded lists are omitted ar
7 min read
Python program to remove duplicate elements index from other list
Given two lists, the task is to write a Python program to remove all the index elements from 2nd list which are duplicate element indices from 1st list. Examples: Input : test_list1 = [3, 5, 6, 5, 3, 7, 8, 6], test_list2 = [1, 7, 6, 3, 7, 9, 10, 11] Output : [1, 7, 6, 9, 10] Explanation : 3, 7 and 1
7 min read
Python | Program to count duplicates in a list of tuples
Given a list of tuples, write a Python program to check if an element of the list has duplicates. If duplicates exist, print the number of occurrences of each duplicate tuple, otherwise print "No Duplicates". Examples: Input : [('a', 'e'), ('b', 'x'), ('b', 'x'), ('a', 'e'), ('b', 'x')] Output : ('a
6 min read
Python program to convert Set into Tuple and Tuple into Set
Let's see how to convert the set into tuple and tuple into the set. For performing the task we are use some methods like tuple(), set(), type(). tuple(): tuple method is used to convert into a tuple. This method accepts other type values as an argument and returns a tuple type value.set(): set metho
7 min read
Python - Convert List of Lists to Tuple of Tuples
Sometimes, while working with Python data, we can have a problem in which we need to perform interconversion of data types. This kind of problem can occur in domains in which we need to get data in particular formats such as Machine Learning. Let us discuss certain ways in which this task can be per
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