In this simple python program, we need to compute the Union of two lists. It is a number-based python program.
For a better understanding of this example, we always recommend you to learn the basic topics of Python programming listed below:
In this simple python program on the list, we need to find the union of two lists. So let us check what is meant by the union. The union is a set operation that can be described as if set A has some elements, and set B has some elements. Union of Set A and B are the total elements of set A and set B, which is not a repeat.
Let us take an example set A { 1, 2, 3, 4} and set B = {3, 5, 7, 4} So the union of set A and B will be U = { 1, 2, 3, 4, 5, 7}.
Now, let us check how we can implement this in the python programming language. Here in this python program, we add the elements in two lists using for loop
and append
operator in python language. After adding the elements in both lists, we apply the union using a built-in function set union()
.
Then print the list using print
statement in python. The set union
function is a built-in function in python programming, which returns all the non-repeating values from all the lists. It is a basic set operation. The basic syntax of the union function will be list.union(*list name) where the list is the list name, and the parameters will be the lists that we want to take the union.
STEP 1: Initialize a list for adding the numbers to the list in the python programming language.
STEP 2: Enter the number of terms by the user and store that value in a variable using the int
and input
method.
STEP 3: Using a for loop
, append
the numbers to the list which is entered by the user.
STEP 4: Initialize the second list.
STEP 5: Accept the number of elements and insert the numbers using append
operators the same as the first list.
STEP 6: Apply the union built-in function to get the union of both the list.
STEP 7: Print the union of the sets using the print
statement in the Python programming language.
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)
un = list(set().union(l1,l2))
print('The Union of two lists is:',un)
Enter size of list 1: 4 Enter any number: 2 Enter any number: 4 Enter any number: 3 Enter any number: 6 Enter size of list 2: 4 Enter any number: 1 Enter any number: 2 Enter any number: 5 Enter any number: 4 The Union of two lists is: [1, 2, 3, 4, 5, 6]