Python | Intersection in Tuple Records Data
Last Updated :
17 Apr, 2023
Sometimes, while working with data, we may have a problem in which we require to find the matching records between two lists that we receive. This is a very common problem and records usually occur as a tuple. Let's discuss certain ways in which this problem can be solved.
Method #1 : Using list comprehension List comprehension can opt as method to perform this task in one line rather than running a loop to find the common element. In this, we just iterate for single list and check if any element occurs in other one.
Python3
# Python3 code to demonstrate working of
# Intersection in Tuple Records Data
# Using list comprehension
# Initializing lists
test_list1 = [('gfg', 1), ('is', 2), ('best', 3)]
test_list2 = [('i', 3), ('love', 4), ('gfg', 1)]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Intersection in Tuple Records Data
# Using list comprehension
res = [ele1 for ele1 in test_list1
for ele2 in test_list2 if ele1 == ele2]
# printing result
print("The Intersection of data records is : " + str(res))
Output : The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)]
The original list 2 is : [('i', 3), ('love', 4), ('gfg', 1)]
The Intersection of data records is : [('gfg', 1)]
Time Complexity: O(n^2), where n is the length of the longer list. In the worst-case scenario where both lists have the same length, the time complexity will be O(n^2).
Auxiliary Space: O(k), where k is the number of common elements in both lists. This is because the result list res will only contain the common elements.
Method #2: Using set.intersection() This task can also be performed in smaller way using the generic set intersection. In this, we first convert the list of records to a set and then perform its intersection using intersection().
Python3
# Python3 code to demonstrate working of
# Intersection in Tuple Records Data
# Using set.intersection()
# Initializing lists
test_list1 = [('gfg', 1), ('is', 2), ('best', 3)]
test_list2 = [('i', 3), ('love', 4), ('gfg', 1)]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
# Intersection in Tuple Records Data
# set.intersection()
res = list(set(test_list1).intersection(set(test_list2)))
# printing result
print("The Intersection of data records is : " + str(res))
Output : The original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)]
The original list 2 is : [('i', 3), ('love', 4), ('gfg', 1)]
The Intersection of data records is : [('gfg', 1)]
Time complexity: O(m+n), where m and n are the lengths of test_list1 and test_list2 respectively.
Auxiliary space: O(m+n), where m and n are the lengths of test_list1 and test_list2 respectively.
Method #3 : Using dict
This method creates two dictionaries from the input lists of tuples, finds the common keys between the two dictionaries, and creates a new list of tuples with the common keys and their corresponding values from the first dictionary.
Python3
# define the two lists of tuples
list1 = [('gfg', 1), ('is', 2), ('best', 3)]
list2 = [('i', 3), ('love', 4), ('gfg', 1)]
# create two dictionaries from the lists
dict1 = dict(list1)
dict2 = dict(list2)
# find the keys that are present in both dictionaries
common_keys = set(dict1.keys()).intersection(set(dict2.keys()))
# create a list of tuples with the common keys and their values
result = [(key, dict1[key]) for key in common_keys]
# print the result
print("The Intersection of data records is :", result)
OutputThe Intersection of data records is : [('gfg', 1)]
Time complexity: O(n)
Auxiliary Space: O(n)
Method #4 : Using List Comprehension and filter() function:
Algorithm:
1. Define two test lists of tuples - test_list1 and test_list2.
2.Use filter() function to filter out the tuples from test_list1 which are present in test_list2.
3. Return the filtered tuples as a list and store it in variable res.
4. Print the result.
Python3
test_list1 = [('gfg', 1), ('is', 2), ('best', 3)]
test_list2 = [('i', 3), ('love', 4), ('gfg', 1)]
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
res = list(filter(lambda t: t in test_list2, test_list1))
print("The Intersection of data records is : " + str(res))
#This code is contributed by Jyothi pinjala
OutputThe original list 1 is : [('gfg', 1), ('is', 2), ('best', 3)]
The original list 2 is : [('i', 3), ('love', 4), ('gfg', 1)]
The Intersection of data records is : [('gfg', 1)]
Time Complexity:
The filter() function has a time complexity of O(n) where n is the length of the iterable being filtered.
In the worst case, all tuples from test_list1 are compared with all tuples from test_list2, giving a time complexity of O(n^2).
Thus, the time complexity of the algorithm is O(n^2).
Auxiliary Space:
The auxiliary space of the algorithm is O(m), where m is the length of the filtered list.
In the worst case, all tuples from test_list1 are present in test_list2, giving a space complexity of O(n).
Thus, the space complexity of the algorithm is O(n).
Method 5 : using a loop to iterate through one of the lists and check if each element exists in the other list.
Here is a step-by-step approach for this method:
- Initialize an empty list called intersection.
- Loop through each tuple in test_list1.
- For each tuple, extract the first element (string) and check if it exists in test_list2 by looping through each tuple in test_list2 and comparing the first element of the tuple.
- If the first element exists in test_list2, append the tuple from test_list1 to intersection.
- Print the intersection list.
Python3
# test data
test_list1 = [('gfg', 1), ('is', 2), ('best', 3)]
test_list2 = [('i', 3), ('love', 4), ('gfg', 1)]
# initialize an empty list
intersection = []
# loop through each tuple in test_list1
for tuple1 in test_list1:
# extract the first element (string)
str1 = tuple1[0]
# loop through each tuple in test_list2
for tuple2 in test_list2:
# extract the first element (string)
str2 = tuple2[0]
# if the strings match, append the tuple from test_list1 to intersection
if str1 == str2:
intersection.append(tuple1)
# print the intersection
print("The intersection of data records is:", intersection)
OutputThe intersection of data records is: [('gfg', 1)]
The time complexity of this method is O(n^2) because it requires iterating through both lists in a nested loop.
The auxiliary space is O(k) where k is the number of common elements in both lists since we only store those common elements in the intersection list.
Method 6: Using the itertools module
- Import the itertools module.
- Use the itertools.product() function to create a Cartesian product of the two lists.
- Use list comprehension to filter the resulting list to only include tuples where the first element of the tuple in test_list1 matches the first element of the tuple in test_list2.
- Use list comprehension to extract the tuples from the resulting list that match the condition in step 3.
- Assign the resulting list to the intersection variable and print it.
Python3
import itertools
test_list1 = [('gfg', 1), ('is', 2), ('best', 3)]
test_list2 = [('i', 3), ('love', 4), ('gfg', 1)]
# use itertools.product() to create a Cartesian product of the two lists
cartesian_product = list(itertools.product(test_list1, test_list2))
# use list comprehension to filter the resulting list
filtered_list = [x for x in cartesian_product if x[0][0] == x[1][0]]
# use list comprehension to extract the tuples that match the condition in step 3
intersection = [x[0] for x in filtered_list]
# print the intersection
print("The intersection of data records is:", intersection)
OutputThe intersection of data records is: [('gfg', 1)]
Time complexity: O(n)
Auxiliary space: O(n)
Similar Reads
Python | Records Intersection Sometimes, while working with tuples, we can have a problem in which we need similar features of two records. This type of application can come in the Data Science domain. Letâs discuss certain ways in which this problem can be solved. Method #1: Using set() + "&" operator This task can be perfo
6 min read
Python | Remove duplicate lists in tuples (Preserving Order) Sometimes, while working with records, we can have a problem in which we need to remove duplicate records. This kind of problem is common in web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + set() In this method, we test fo
7 min read
Python - Remove nested records from tuple Sometimes, while working with records, we can have a problem in which an element of a record is another tuple records and we might have to remove the nested records. This is a problem which does not occur commonly, but having a solution to it is useful. Letâs discuss certain way in which this task c
5 min read
Multiple Sets Intersection in Python In this article, a List of sets is given our task is to write a program to perform their intersection using Python. Examples of finding the intersection of multiple setsInput : test_list = [{5, 3, 6, 7}, {1, 3, 5, 2}, {7, 3, 8, 5}, {8, 4, 5, 3}] Output : {3, 5} Explanation : 3 and 5 is present in al
2 min read
Creating Sets of Tuples in Python Tuples are an essential data structure in Python, providing a way to store ordered and immutable sequences of elements. When combined with sets, which are unordered collections of unique elements, you can create powerful and efficient data structures for various applications. In this article, we wil
3 min read
Python | Test if tuple is distinct Sometimes, while working with records, we have a problem in which we need to find if all elements of tuple are different. This can have applications in many domains including web development. Let's discuss certain ways in which this task can be performed. Method #1 : Using loop This is a brute force
4 min read
Python - Remove all duplicate occurring tuple records Sometimes, while working with records, we can have a problem of removing those records which occur more than once. This kind of application can occur in web development domain. Letâs discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + set() + count() Init
6 min read
How to Take List of Tuples as Input in Python? Lists of tuples are useful data structures in Python and commonly used when you need to group related elements together while maintaining immutability within each group. We may need to take input for a list of tuples from the user. This article will explore different methods to take a list of tuples
3 min read
Python - Records with Value at K index Sometimes, while working with records, we might have a problem in which we need to find all the tuples of elements for a particular value at a particular Kth position of tuple. This seems to be a peculiar problem but while working with many keys in records, we encounter this problem. Letâs discuss c
8 min read