by BehindJava

Write a program to Find the Union of two Lists in Python

Home » python » Write a program to Find the Union of two Lists in Python

In this tutorial we are going to learn about finding the Union of two Lists in Python.

Python Program to Find the Union of two Lists

l1 = []
num1 = int(input('Enter size of list 1: '))
for n in range(num1):
    numbers1 = int(input('Enter any number:'))
    l1.append(numbers1)
 
l2 = []
num2 = int(input('Enter size of list 2:'))
for n in range(num2):
    numbers2 = int(input('Enter any number:'))
    l2.append(numbers2)
 
union = list(set().union(l1,l2))
 
print('The Union of two lists is:',union)

Explanation

  1. User must enter the number of elements in the list and store it in a variable.
  2. User must enter the values to the same number of elements into the list.
  3. The append function obtains each element from the user and adds the same to the end of the list as many times as the number of elements taken.
  4. The same of 2 and 3 is done for the second list also.
  5. The union function accepts two lists and returns the list which is the union of the two lists, i.e, all the values from list 1 and 2 without redundancy.
  6. The set function in the union function accepts a list and returns the list after elimination of redundant values.
  7. The lists are passed to the union function and the returned list is printed.