Python subtract lists element by element | Example code

Use zip() to Python subtract lists element by element in Python.

 zip(iterator1, iterator2) 

Example subtract lists element by element in Python

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

list1 = [1, 2, 3]
list2 = [1, 1, 1]
res = []

obj = zip(list1, list2)

for i, j in obj:
    res.append(i - j)

print(res)

Output:

Python subtract lists element by element

Anothe example

Simple Python code to subtract if an element in the first list is greater than the element in the second list else we output the element of the first list.

l1 = [10, 20, 30, 40, 50, 60]
l2 = [60, 50, 40, 30, 20, 10]

# using zip()
res = [e1 - e2 if e1 > e2 else e1 for (e1, e2) in zip(l1, l2)]

print(res)

Output: [10, 20, 30, 10, 30, 50]

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

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

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