Skip to content

Python subtraction between two lists | Example code

  • by

Use the zip() function to perform a subtraction between two lists in Python. This function will take two iterators and return a zip object.

Example subtraction between two lists in Python

Simple example code subtracting two lists with the same length containing elements of the same type. Where subtracts the values at each index in one from the other.

Using for-loop to iterate over the zip object subtract the lists’ elements from each other and store the result in a list.

list1 = [5, 2, 4]
list2 = [4, 5, 6]

res = []

zip_object = zip(list1, list2)

for i, k in zip_object:
    res.append(i - k)

print(res)

Output:

Python subtraction between two lists

Using List Comprehension:

You can use list comprehension to subtract one list from another by iterating through the elements of the first list and including only those that are not in the second list.

list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]

result = [x for x in list1 if x not in list2]

print(result)  # Output: [1, 2]

Using Set Difference:

You can convert the lists to sets and then use the set difference operation (-) to find the elements that are unique to the first list.

list1 = [1, 2, 3, 4, 5]
list2 = [3, 4, 5, 6, 7]

set1 = set(list1)
set2 = set(list2)

result = list(set1 - set2)

print(result)  # Output: [1, 2]

Do comment if you have any doubts or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *