Categories
Python Answers

How to do list subtraction with Python?

Spread the love

Sometimes, we want to do list subtraction with Python

In this article, we’ll look at how to do list subtraction with Python

How to do list subtraction with Python??

To do list subtraction with Python, we can convert the 2 lists to sets and then do subtract with them.

And then we can convert the difference back to a list.

For instance, we write:

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
y = [1, 3, 5, 7, 9]
z = list(set(x) - set(y))
print(z)

We convert x and y to sets with the set function.

Then we get the set difference with set(x) - set(y).

Finally, we convert the set difference set back to a list with list.

Therefore, z is [0, 2, 4, 6, 8].

Conclusion

To do list subtraction with Python, we can convert the 2 lists to sets and then do subtract with them.

And then we can convert the difference back to a list.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *