This is a Python Program to find the union of two lists.
The program takes two lists and finds the unions of the two lists.
1. Define a function which accepts two lists and returns the union of them.
2. Declare two empty lists and initialise to an empty list.
3. Consider a for loop to accept values for two lists.
4. Take the number of elements in the list and store it in a variable.
5. Accept the values into the list using another for loop and insert into the list.
6. Repeat 4 and 5 for the second list also.
7. Find the union of the two lists.
8. Print the union.
9. Exit.
Here is source code of the Python Program to find the union of two lists. The program output is also shown below.
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)
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.
Case 1: Enter size of list 1: 4 Enter any number: 20 Enter any number: 40 Enter any number: 30 Enter any number: 60 Enter size of list 2: 4 Enter any number: 10 Enter any number: 20 Enter any number: 50 Enter any number: 40 The Union of two lists is: [40, 10, 50, 20, 60, 30] Case 2: Enter size of list 1: 3 Enter any number: 5 Enter any number: 6 Enter any number: 7 Enter size of list 2: 2 Enter any number: 8 Enter any number: 9 The Union of two lists is: [8, 9, 5, 6, 7]
Sanfoundry Global Education & Learning Series – Python Programs.
To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.
- Practice Programming MCQs
- Check Information Technology Books
- Check Python Books
- Apply for Python Internship
- Apply for Programming Internship