Python list minus list | Example code

  • by

Use the zip method to list minus list in Python. You have to also use for-loop to iterate over the zip object and subtract the lists’ elements from each other and store the result in a list.

If you are looking to find a difference between lists then follow this tutorial: –Python list difference | Example code

Python list minus list example

Simple example code. Let’s first what actually means is to compute a list by minus the corresponding elements in two lists.

For example, if the lists are [9,5,14] and [1,4,6] we want as the result the list [8,1,8] by computing the differences 9–1,5–4,14–6.

list1 = [9, 5, 14]
list2 = [1, 4, 6]

def subtract(L1, L2):
    return [x1 - x2 for x1, x2 in zip(L1, L2)]

print(subtract(list1, list2))


Python list minus list

Another Example

Python list minus list element-wise (component-wise subtraction.)

list1 = [9, 5, 14]
list2 = [1, 4, 6]
difference = []

zip_object = zip(list1, list2)

for list1_i, list2_i in zip_object:
    difference.append(list1_i - list2_i)


Output: [8, 1, 8]

Do comment if you have any doubts and suggestions on this Python List code.

Note: IDE: PyCharm 2021.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 *

This site uses Akismet to reduce spam. Learn how your comment data is processed.