Subtracting two lists in Python


Python tip:

To subtract two lists (element by element), you can use a list comprehension and zip.

zip iterates over both lists -> you receive elements with the same index.

The list comprehension then creates a new list containing subtracted values.

👇

first = [1, 5, 7]
second = [5, 3, 0]

print([xi - yi for xi, yi in zip(first, second)])
# => [-4, 2, 7]