Skip to content
Related Articles

Related Articles

Python | Records Union
  • Last Updated : 23 Jan, 2020

Sometimes, while working with data, we may have a problem in which we require to find all records between two lists that we receive. This is a very common problem and records usually occurs as a tuple. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using list comprehension
List comprehension can be opted as method to perform this task in one line rather than running a loop to find the union elements. In this, we just iterate for single list and check if any element occurs in other one. If no, we again populate the made list.




# Python3 code to demonstrate working of
# Records Union
# 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))
  
# Records Union
# Using list comprehension
res1 = [ele1 for ele1 in test_list1]
res2 = [ele2 for ele2 in test_list2 if ele2 not in res1]
res = res1 + res2
  
# printing result
print("The union 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 union of data records is : [('gfg', 1), ('is', 2), ('best', 3), ('i', 3), ('love', 4)]

 

Method #2 : Using set.union()
This task can also be performed in smaller way using the generic set union. In this, we first convert the list of records to a set and then perform its union using union().






# Python3 code to demonstrate working of
# Records Union
# Using set.union()
  
# 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))
  
# Records Union
# set.union()
res = list(set(test_list1).union(set(test_list2)))
  
# printing result
print("The union 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 union of data records is : [('gfg', 1), ('is', 2), ('best', 3), ('i', 3), ('love', 4)]

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course

My Personal Notes arrow_drop_up
Recommended Articles
Page :