Home » How to find Union of two lists in Python

How to find Union of two lists in Python

How to find Union of two lists in Python

Hello everybody, welcome back to Programming In Python. Here in this post am going to tell you how to find the union of two lists in Python. Generally, Union means getting all the unique elements in both lists. So here I will take two lists and convert them to a set and then apply the union function on it to find all the unique elements n both lists. Not only for two lists the same way we can find the union of any number of lists.

You can watch this video on YouTube here

Program on GitHub

Union of two lists – Code Visualization

Task:

To find the Union of two lists in Python.

Approach:

  • Read the input number asking for the length of the list using input() or raw_input().
  • Initialize an empty list.lst = []
  • Read each number using afor loop
  • In the for loop append each number to the list.
  • Repeat the above 4 points for the second list lst2[] as well.
  • Find union of two lists by converting lists into sets and using Python’s union function `set().union(lst, lst2)`
  • Print the result.

Program on GitHub

Program:

__author__ = 'Avinash'

lst = []
num = int(input("Enter size of list 1: \t"))
for n in range(num):
    numbers = int(input("Enter any number: \t"))
    lst.append(numbers)

lst2 = []
num2 = int(input("Enter size of list 2: \t"))
for n in range(num2):
    numbers2 = int(input("Enter any number: \t"))
    lst2.append(numbers2)

union = list(set().union(lst, lst2))

print("\nThe Union of two lists is \t", union)

Program on GitHub

Output:

Union of two lists in Python
Union of two lists in Python – Programming In Python

For more such programs or examples on Lists, follow this link.

Online Python Compiler

Leave a Reply

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