Q:

Python | Program to find the differences of two lists

belongs to collection: Python List Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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']

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python List Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Program to Print the index of first match... >>
<< Python | Program to sort the elements of given lis...