Home » Python programs

Python | Program to find the differences of two lists

Here, we are going to learn how to find the differences of two lists in the python? To find the differences, lists should be cast types to the sets and then use minus (-) operator to get the elements which are not in second list.
Submitted by IncludeHelp, on July 25, 2018

Given two lists of integers, we have to find the differences i.e. the elements which are not exists in second lists.

Example:

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

    Output:
    Different elements:
    [40, 50]

Logic:

To find the differences of the lists, we are using set() Method, in this way, we have to explicitly convert lists into sets and then subtract the set converted lists, the result will be the elements which are not exist in the second.

Program to find difference 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 mixed type of elements, printing 1) the elements which are not exist in list2 and 2) the elements which are not exists 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']





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.