Python | Difference between the two lists

Python Methods and Functions

There are various ways to differentiate between two lists. In this article, we will see the two most important ways in which this can be done. One with the set () method and the other — without him. 
Examples:

 Input: list1 = [10, 15, 20, 25, 30, 35, 40] list2 = [25, 40, 35] Output: [10, 20, 30, 15] Explanation: resultant list = list1 - list2 
  1. Using set ()
    In this method, we explicitly convert lists to sets and then just shrink one from the other using the subtraction operator. For more information on the set, visit

    # Python code t gets the difference between the two lists
    # Using set ()

    def Diff (li1, li2):

    return ( list ( set (li1) - set (li2)))

      
    Driver code

    li1 = [ 10 , 15 , 20 , 25 , 30 , 35 , 40 ]

    li2 = [ 25 , 40 , 35 ]

    print (Diff (li1, li2))

    Output:

     [10, 20, 30, 15] 
  2. Without using set ()
    In this method, we use a basic combination technique to copy items from both lists, regularly checking whether one is present in the other or not.

    # Python code t gets the difference between the two lists
    # Not used set ()

    def Diff (li1, li2):

    li_dif = [i for i in li1 + li2 if i not in li1 or i not in li2]

    return li_dif

     
    Driver code

    li1 = [ 10 , 15 , 20 , 25 , 30 , 35 , 40 ]

    li2 = [ 25 , 40 , 35 ]

    li3 = Diff (li1, li2)

    print (li3)

    Output:

     [10, 20, 30, 15] 




Tutorials