In this tutorial, we will walk through the process of subtracting two lists in Python. Python, a powerful and flexible programming language, offers various methods to perform this operation.
We’ll guide you through using these methods, including list comprehension, the filter() function, and the set() function.
1. List Comprehension
In Python, list comprehension provides a concise way to manipulate lists. It’s a syntactic construct that enables lists to be created from other lists or any iterable object. To subtract one list from another using list comprehension, check if an element from the first list is present in the second. If it’s not, then include this in the outcome.
1 2 3 |
list1 = [1, 2, 3, 4, 5] list2 = [2, 3] list3 = [i for i in list1 if i not in list2] |
We get the output:
1 |
[1, 4, 5] |
2. Using the filter() Function
The filter() function in Python takes a function and a list as arguments. This function offers an elegant way to filter out elements from a list that do not satisfy the requirements. Here’s how you can use the filter() function to subtract two lists:
1 2 3 |
list1 = [1, 2, 3, 4, 5] list2 = [2, 3] list3 = list(filter(lambda x: x not in list2, list1)) |
The result is:
1 |
[1, 4, 5] |
3. Using the set() Function
Python’s set() function transforms a list into a set—a collection of unique elements achieved through the concept of Hashing. You can use the – operator to subtract two sets, then convert the resultant set back to a list:
1 2 3 |
list1 = [1, 2, 3, 4, 5] list2 = [2, 3] list3 = list(set(list1) - set(list2)) |
The output is:
1 |
[1, 4, 5] |
Full code
The full implementation of list subtraction using different methods:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Using list comprehension list1 = [1, 2, 3, 4, 5] list2 = [2, 3] list3 = [i for i in list1 if i not in list2] print(list3) # Using the filter function list1 = [1, 2, 3, 4, 5] list2 = [2, 3] list3 = list(filter(lambda x: x not in list2, list1)) print(list3) # Using the set function list1 = [1, 2, 3, 4, 5] list2 = [2, 3] list3 = list(set(list1) - set(list2)) print(list3) |
Conclusion
Python provides diverse and straightforward ways to subtract lists, from using list comprehension to the filter() function and the set() function.
Depending on your specific needs and the characteristics of your data, you can use these methods interchangeably. This flexibility makes Python a powerful tool for managing and manipulating data in lists.