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 and 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 and 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

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

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.