Subtract list from another list python

This tutorial demonstrates how to perform the list subtraction, or in other words, list minus list in Python.

As defined by the set theory in mathematics, the difference of two sets refers to the elements from one set that do not exist in the other set.

For example, if we declare these two lists:

list1 = [1, 2, 4] list2 = [2, 3]

The difference of list1 - list2 would be [1, 4], while list2 - list1 would be [3].

Set theory operations are supported in Python. However, only the set data type support these operations. Therefore, to use the set operation, lists have to be converted into sets. This is possible by wrapping a list around the function set().

Converting a list to a set will remove any type of order and remove duplicate values from the list.

listA = [1, 2, 4, 7, 9, 11, 11, 14, 14] listB = [2, 3, 7, 8, 11, 13, 13, 16] setA = set(listA) setB = set(listB) print('A - B = ', setA - setB)

Output:

A - B = {1, 4, 9, 14}

The result outputs the difference between the two sets and removes the duplicate values.

We can use the function list() to convert the result from a set to a list.

listA = [1, 2, 4, 7, 9, 11, 11, 14, 14] listB = [2, 3, 7, 8, 11, 13, 13, 16] setA = set(listA) setB = set(listB) list_diff = list(setA - setB) print('A - B: ', list_diff)

Output:

A - B: [1, 4, 9, 14]

Use List Comprehension to Get List Difference in Python

List comprehension can be used to check if an element exists only in the first list but does not exist in the second list. This solution makes it possible to perform the difference operation without converting the list to a set.

listA = [1, 2, 4, 7, 9, 11, 11, 14, 14] listB = [2, 3, 7, 8, 11, 13, 13, 16] listSub = [elem for elem in listA if elem not in listB] print('A - B =', listSub)

Output:

A - B = [1, 4, 9, 14, 14]

This solution does not mess with the order of the list and removes duplicates.

However, the value 11 is repeated twice in listA, and both iterations of 11 are removed from the result of A - B since 11 exists in both sets. This behavior is as expected.

DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python List

  • Convert a Dictionary to a List in Python
  • Remove All the Occurrences of an Element From a List in Python
  • Remove Duplicates From List in Python
  • Get the Average of a List in Python
  • There are various ways in which the difference between two lists can be generated. In this article, we will see the two most important ways in which this can be done. One by using the set() method, and another by not using it. 
     

    Examples:  



    Input : list1 = [10, 15, 20, 25, 30, 35, 40] list2 = [25, 40, 35] Output : [10, 20, 30, 15] Explanation: resultant list = list1 - list2

     Note: When you have multiple same elements then this would not work. In that case, this code will simply remove the same elements.
    In that case, you can maintain a count of each element in both lists.

    By the use of set():  

    In this method, we convert the lists into sets explicitly and then simply reduce one from the other using the subtract operator. For more reference on set visit Sets in Python. 
     

    Example: 

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

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

    Output : 
     

    [10, 20, 30, 15]

    Without using the set():  

    In this method, we use the basic combination technique to copy elements from both the list with a regular check if one is present in the other or not. 
     

    Example:

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

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

    Output : 

    [10, 20, 30, 15]

    Article Tags :

    Practice Tags :

    Given two list, If element in first list in greater than element in second list, then subtract it, else return the element of first list only.
    Examples:
     

    Input: l1 = [10, 20, 30, 40, 50, 60] l2 = [60, 50, 40, 30, 20, 10] Output: [10, 20, 30, 10, 30, 50] Input: l1 = [15, 9, 10, 56, 23, 78, 5, 4, 9] l2 = [9, 4, 5, 36, 47, 26, 10, 45, 87] Output: [6, 5, 5, 20, 23, 52, 5, 4, 9]

    Method 1: The naive approach is to traverse both list simultaneously and if the element in first list in greater than element in second list, then subtract it, else if the element in first list in smaller than element in second list, then return element of first list only.
     



    Input1 = [10, 20, 30, 40, 50, 60]

    Input2 = [60, 50, 40, 30, 20, 10]

    for i in range(len(Input1)):

        if Input1[i] > Input2[i]:

            Output.append(Input1[i] - Input2[i])

    print("Original list are :")

    print("\nOutput list is")

    Output:
     

    Original list are : [10, 20, 30, 40, 50, 60] [60, 50, 40, 30, 20, 10] Output list is [10, 20, 30, 10, 30, 50]

    Method 2: Using zip() we subtract if element in first list is greater than element in second list, else we output element of first list.
     

    Input1 = [10, 20, 30, 40, 50, 60]

    Input2 = [60, 50, 40, 30, 20, 10]

    Output =[e1-e2 if e1>e2 else e1 for (e1, e2) in zip(Input1, Input2)]

    print("Original list are :")

    print("\nOutput list is")

    Output:
     

    Original list are : [10, 20, 30, 40, 50, 60] [60, 50, 40, 30, 20, 10] Output list is [10, 20, 30, 10, 30, 50]

    Method 3: Using list comprehension.
     

    Input1 = [10, 20, 30, 40, 50, 60]

    Input2 = [60, 50, 40, 30, 20, 10]

    Output = [Input1[i]-Input2[i] if Input1[i] > Input2[i] \

              else Input1[i] for i in range(len(Input1))]

    print("Original list are :")

    print("\nOutput list is")

    Output: 
     

    Original list are : [10, 20, 30, 40, 50, 60] [60, 50, 40, 30, 20, 10] Output list is [10, 20, 30, 10, 30, 50]

    Method 4: Using numpy() to complete the above task.
     

    Input1 = np.array([10, 20, 30, 40, 50, 60])

    Input2 = np.array([60, 50, 40, 30, 20, 10])

    Output = np.where(Input1 >= Input2, Input1 - Input2, Input1)

    print("Original list are :")

    print("\nOutput list is")

    Output:
     

    Original list are : [10 20 30 40 50 60] [60 50 40 30 20 10] Output list is [10 20 30 10 30 50]

    Article Tags :