Skip to content

Python subtract lists element by element | Example code

  • by

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

 zip(iterator1, iterator2) 

Example subtract lists element by element in Python

A 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)



Python subtract lists element by element

Another 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)]


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

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

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 *

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