How To Quickly Compare Two Tuples

How To Quickly Compare Two Tuples

Python Tuples are compared position by position, meaning the first item of the first Tuple is compared to the first item of the second Tuple, and so on. To implement a comparison while keeping into account unique/different values we need to convert the Tuples to Sets, which will take the Tuples and only take unique values.

For example is you would like to see which values are the same in two Tuples:

a = (6, 1, 2, 3, 4, 5)
b = (9, 8, 7, 6, 5)
print(set(a) & set(b))
# => {5, 6}

To figure out which values are different between the first and the second Tuple:

a = (6, 1, 2, 3, 4, 5)
b = (9, 8, 7, 6, 5)
print(set(a) - set(b))
# => {1, 2, 3, 4}

And finally to see which values are different between the second and the first Tuple:

a = (6, 1, 2, 3, 4, 5)
b = (9, 8, 7, 6, 5)
print(set(b) - set(a))
# => {8, 9, 7}

Now even though all these look awesome, there are downsides:

You can always convert the Set back to a Tuple with Python's tuple constructor, so this is an easy fix and if you don't care about keeping duplicate or the same order of the values this is a very efficient way to accomplish Tuple comparison. But what if there was a more efficient way; well, there is!

List comprehension is an elegant way of creating lists. The format look like this [expression + context].

With list comprehension you can go over all the values in the first list and ignore them is they are in the second list.

a = (6, 1, 2, 3, 4, 5)
b = (9, 8, 7, 6, 5)
print([x for x in a if x not in set(b)])
# => {1, 2, 3, 4}

With this technique the result is a list that can be quickly converted to a Tuple with Python's tuple constructor, the order of the values and duplicate values are maintained.

Join me on Twitter if you would like to continue the conversation. Best!