Python subtract two lists[4 Easy Ways] - JSON Viewer

Python subtract two lists[4 Easy Ways]

In this page, we will learn different techniques to python subtract two lists.

Types of List Subtraction in python

Using List Comprehension

List comprehension is a python technique to create new lists using the old lists. It is used to add the conditional element in the new list by using the single line of code .List comprehension is a powerful tool for creating new lists in Python, especially when working with large datasets.

syntax:

new_list = [expression for item in iterable if condition]

new_list: name of new list

expression: value to be assigned on each item

item: item in list

iterable: list to iterate

condition (optional): a condition to add the element in new list

For Example –

students1 = ["John", "Dave" , "Daisy" ,"Mark" , "Tom"]
students2 = ["John" , "Dave"]
final = [item for item in students1 if item not in students2]
print(final)

This code creates two lists students1 and students2, which contain the names of some students. then using a list comprehension to create a new list called final, which includes all the names in students1 that are not in students2.

Output –

['Daisy', 'Mark', 'Tom']

Using set difference to subtract lists

  • The set difference operation involves converting the lists to sets and taking the set difference between them with the “-” operator..
  • The set difference consists of all the elements that are in the first set, but not in the second set. The result of set operation is converted back into a list and assigned to the variable.

Syntax –

result = list(set(list2) - set(list1))

For Example –

vehicle1 = ["Honda" , "Toyota", "Suzuki" ,"Nexa" ,"Tata"]
vehicle2 = ["Nexa" ,"Tata"]
final = list(set(vehicle1) - set(vehicle2))
print(final)

The code creates two lists vehicle1 and vehicle2, which contain the names of some vehicles. The code then uses the set difference method to create a new list called final, which includes all the names in vehicle1 that are not also in vehicle2. Finally, the code prints out the list final.

Output –

['Suzuki', 'Honda', 'Toyota']

Using Numpy to Find the Difference Between Two Lists in Python

numpy.setdiff1d is a method in the NumPy library in Python that returns the set difference of two arrays. In other words, it returns the unique values in the first array that are not present in the second array.

Syntax –

numpy.setdiff1d(ar1, ar2, assume_unique=False)

The method returns a sorted, 1-dimensional array of unique values in ar1 that are not present in ar2.

For Example-

import numpy as np
words1 = ["hello" , "goom" , "welcome" , "user" , "python"]
words2 = ["user" , "python"]
word_diff = np.setdiff1d(words1, words2)
print(word_diff)

Output –

['goom' 'hello' 'welcome']

Using symmetric_difference to Find the Difference Between Two Lists in Python

The element which are either in first list or second list are returned using this method.this also uses conversion of list to sets

Syntax –

set(lis11).symmetric_difference(set(listt2))

For example –

List1 = [1, 2, 3, 4, 5]
List22 = [3, 4, 5, 6, 7]
diff = set(List1).symmetric_difference(set(List22))
print(list(diff))

Output –

[1, 2, 6, 7]

Errors while working with list subtraction

Name Errors:

This type of errors are caused If you mistype the name of a variable that you are trying to subtract from, you may get a NameError. This is a common mistake when you are using variables with similar names. To avoid this error, always use proper names of your variables and make sure they are spelled correctly.

For Example –

vehicle1 = ["Honda" , "Toyota", "Suzuki" ,"Nexa" ,"Tata"]
vehicle = ["Nexa" ,"Tata"]
final = list(set(vehicle1) - set(vehicle2))
print(final)

Output –

File "/home/main.py", line 4, in <module>
NameError: name 'vehicle2' is not defined. Did you mean: 'vehicle1'?

Order of Elements:

sets are unordered, and the set difference only takes into account the elements themselves so when using the set difference method to subtract one list from another, the resulting list may not keep the order of the original list.

For example –

users1 = ["Mark", "Steve" , "Jack" , "Stephen" , "Natasha"]
users2 = ["Stephen" , "Jack"]
final_users = list(set(users1) - set(users2))
print(final_users)

Output –

['Natasha', 'Steve', 'Mark']

here the order of the original list is not maintained .

to avoid this error we can use list comprehension

For Example –

users1 = ["Mark", "Steve" , "Jack" , "Stephen" , "Natasha"]
users2 = ["Stephen" , "Jack"]
final_users = [user for user in users1 if user not in users2]
print(final_users)

Output –

['Mark', 'Steve', 'Natasha']

here the order of original list is maintained

Use Cases of list subtraction –

Removing Duplicates:

If you have two lists that contain duplicate elements, you can use list subtraction to create a new list that contains only the elements that appear in one list and not the other. This is because the set difference method used in list subtraction automatically removes duplicates.

For Example –

list1 = [10 ,20, 20, 20, 30 ,40, 50]
list2 = [20 ,20]
unique = [item for item in list1 if item not in list2]
print(unique)

Output –

[10, 30, 40, 50]

Filtering Lists:

List subtraction can also be used to filter lists based on specific criteria.

For example,

you can create a new list that contains only the elements that are in list and are greater than 20

list1 = [10 ,20, 20, 20, 30 ,40, 50]
list2 = [20 ,20 ,30 ,40]
unique = [item for item in list1 if item in list2 and item >20]
print(unique)

For example –

[30, 40]