Python Program to Find the Union of Two Lists

Finding the union of two lists is a common operation in programming, particularly when dealing with data manipulation and set operations. The union of two lists refers to the operation of combining both lists to create a new list that contains all unique elements from both lists, without any duplicates. In other words, the union of two lists contains all distinct elements present in either or both of the original lists.

Problem Statement

You are given two lists, List A and List B, containing integer elements. Your task is to write a python program that finds the union of these two lists. The union of two lists is defined as a new list that contains all unique elements from both List A and List B, without any duplicates.

Python Program to Find the Union of Two Lists

def find_union(list1, list2):
    union = list(set(list1) | set(list2))
    return union

# Example lists
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]

union_result = find_union(list1, list2)
print("Union of the two lists:", union_result)

How it Works

  1. Function Definition (find_union):
    • The function find_union is defined to take two lists as parameters: list1 and list2.
  2. Conversion to Sets:
    • Inside the function, both list1 and list2 are converted into sets using the set() function. This step removes any duplicate elements from each list, as sets do not allow duplicates.
  3. Union Operation:
    • The | (pipe) operator is used to perform a union operation between the two sets obtained from list1 and list2. This operation combines the elements of both sets while discarding duplicate values.
  4. Conversion Back to List:
    • The resulting set from the union operation is then converted back into a list using the list() constructor. This step is necessary to present the final result as a list.
  5. Output:
    • The union list, which now contains all the unique elements from both list1 and list2, is returned from the function.
    • The program then assigns the returned list to the variable union_result.
  6. Print Result:
    • Finally, the program prints the contents of the union_result list, which is the union of the two input lists, in the following format: “Union of the two lists: [1, 2, 3, 4, 5, 6, 7, 8]”.

Input/ Output

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

In this Python program, we will create a singly linked list and remove duplicate elements from it. A linked list...
This Python program solves the Celebrity Problem by finding a person who is known by everyone but does not know...
This Python program uses a recursive approach to solve the n-Queens problem. It explores all possible combinations of queen placements...