How to find Union of two lists in Python

Hello everybody, welcome back to programminginpython.com. 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 the lists. So here I will take two lists and convert them to set and then apply the union function on it to find all the unique elements n both the 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 Union of two lists in python.

Approach:

  • Read input number asking for the length of the list using input() or raw_input().
  • Initialise 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:

Program on Github

Output:

Union of two lists - programminginpython.com
Union of two lists – programminginpython.com
Union of two lists - programminginpython.com
Union of two lists – programminginpython.com

Leave a Reply