Learn How to Subtract Lists with Simple Steps
In this guide, you will learn how to subtract two lists in Python. The built-in function subtraction works differently for sets and lists. …
In this guide, you will learn how to subtract two lists in Python. The built-in function subtraction works differently for sets and lists.
Subtraction of Lists The most common operation on lists is list subtraction (or difference). This operation takes two input lists and removes the elements present in the second list from the first one, leaving only the unique items from the first list. Here’s how to do it:
list1 = [1, 2, 3, 4, 5]
list2 = [2, 3, 4, 6]
result_subtraction = [value for value in list1 if value not in list2]
print(result_subtraction) # Output: [1, 5]
Note that the order of elements in list1
is preserved after subtraction.
The not in
keyword works with the if
statement to iterate over each value from list1
. If a value does not exist in list2
, it gets added to the resultant list, which is then printed. This result will be [1, 5]
, as 2, 3 and 4
are present in both lists.
The output of this operation depends on the order of elements. The common approach is using set operations when you don’t care about the order of elements. For more advanced list differences, like keeping only the items that appear in first list but not second or vice versa, you might need to adjust this code slightly depending on your specific needs.
Remember: This operation will remove duplicates from list1
as well. So if list1
contains repeated elements and you want those preserved in result, you would use a different approach.