Open In App

Python Program to find tuple indices from other tuple list

Last Updated : 30 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  1. Initialize a list of tuples named test_list containing some tuples.
  2. Print the original list of tuples using the print() function and str() function to convert the list into a string.
  3. Initialize another list of tuples named search_tup containing some tuples.
  4. 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.
  5. 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.
  6. 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))


Output

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


Output

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


Output

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


Output

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

  1. Initialize an empty list res to store the indices of matching tuples.
  2. Iterate over each tuple tup in the search_tup list.
  3. Iterate over each tuple lst_tup in the test_list list.
  4. 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.
  5. 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))


Output

The 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 | Indices list of matching element from other list
Sometimes, while working with Python list, we have a problem in which we have to search for an element in list. But this can be extended to a list and need to find the exact places where elements occur in another list. Let's discuss certain ways in which this task can be performed. Method #1: Using loop + count() This is the brute method to perform
7 min read
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)]] Output : [(4, 10), (5, 13)] Explanation : All co
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), (19, 22), (28, 30), (31, 50)], test_list2 = [(10, 12
11 min read
Python program to get the indices of each element of one list in another list
Given 2 lists, get all the indices of all occurrence of each element in list2 from list1. Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 4] Output : [[3], [1, 9], [0, 7]] Explanation : 5 is present at 1st and 9th index. Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 8] Output : [[3], [1, 9],
7 min read
Python | Sort tuple list by Nth element of tuple
Sometimes, while working with Python list, we can come across a problem in which we need to sort the list according to any tuple element. These must be a generic way to perform the sort by particular tuple index. This has a good utility in web development domain. Let's discuss certain ways in which this task can be performed. Method #1: Using sort(
8 min read
Python - Flatten tuple of List to tuple
Sometimes, while working with Python Tuples, we can have a problem in which we need to perform the flattening of tuples, which have listed as their constituent elements. This kind of problem is common in data domains such as Machine Learning. Let's discuss certain ways in which this task can be performed. Input : test_tuple = ([5], [6], [3], [8]) O
7 min read
NumPy indices() Method | Create Array of Indices
The indices() method returns an array representing the indices of a grid. It computes an array where the subarrays contain index values 0, 1, … varying only along the corresponding axis. Example C/C++ Code import numpy as np gfg = np.indices((2, 3)) print (gfg) Output : [[[0 0 0] [1 1 1]] [[0 1 2] [0 1 2]]]Syntax numpy.indices(dimensions, dtype, sp
2 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 method is to convert other type values to set this meth
7 min read
Python program to create a list of tuples from given list having number and its cube in each tuple
Given a list of numbers of list, write a Python program to create a list of tuples having first element as the number and second element as the cube of the number. Example: Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)] Input: list = [9, 5, 6] Output: [(9, 729), (5, 125), (6, 216)] Method #1 : Using pow() function.We can use list compreh
5 min read
Python Program to Convert Tuple Value List to List of Tuples
Given a dictionary with values as a tuple list, convert it to a key-mapped list of tuples. Input : test_dict = {'Gfg' : [(5, ), (6, )], 'is' : [(5, )], 'best' :[(7, )]} Output : [('Gfg', 5), ('Gfg', 6), ('is', 5), ('best', 7)] Explanation : Keys grouped with values.Convert Tuple Value List to List of Tuples Using loop + * operator + items() This is
8 min read
Practice Tags :