Python Program to find the differences between two lists

Here, we will figure out how to discover the distinctions of two lists in the python? To discover the distinctions, lists ought to be thrown sorts to the sets and afterwards utilize short (- ) administrator to get the components which are not in the second list.

Given two lists of integers, we need to discover the distinctions, for example, the components which do not exist in second lists.

Example:

    Input:
    List1 = [10, 20, 30, 40, 50]
    List2 = [10, 20, 30, 60, 70]

    Output:
    Different elements:
    [40, 50]

Logic:

To discover the distinctions of the lists, we are utilizing set() Method, along these lines, we need to unequivocally change over lists into sets and afterwards subtract the set changed over lists, the outcome will be the components which do not exist in the second.

Program to discover contrast of two lists in Python:

# list1 - first list of the integers
# lists2 - second list of the integers
list1 = [10, 20, 30, 40, 50]
list2 = [10, 20, 30, 60, 70]

# printing lists 
print "list1:", list1
print "list2:", list2

# finding and printing differences of the lists
print "Difference elements:"
print (list (set(list1) - set (list2)))

Output:

    list1: [10, 20, 30, 40, 50]
    list2: [10, 20, 30, 60, 70]
    Difference elements:
    [40, 50]

Program 2: with blended sort of components, printing 1) the components which do not exist in list2 and 2) the components which do not exist in list1:

# list1 - first list with mixed type elements
# lists2 - second list with mixed type elements
list1 = ["Amit", "Shukla", 21, "New Delhi"]
list2 = ["Aman", "Shukla", 21, "Mumbai"]

# printing lists 
print "list1:", list1
print "list2:", list2

# finding and printing differences of the lists
print "Elements not exists in list2:"
print (list (set(list1) - set (list2)))

print "Elements not exists in list1:"
print (list (set(list2) - set (list1)))

Output:

    list1: ['Amit', 'Shukla', 21, 'New Delhi']
    list2: ['Aman', 'Shukla', 21, 'Mumbai']
    Elements not exists in list2:
    ['Amit', 'New Delhi']
    Elements not exists in list1:
    ['Aman', 'Mumbai']

Leave a Comment

error: Alert: Content is protected!!