Python tuple subtraction

Python doesn't support tuple subtraction and - operand.

a = (5, 6, 7)
b = (5, 6)

c = a - b

# TypeError: unsupported operand type(s) for -: 'tuple' and 'tuple'

But you can add tuples using + operator. The following is the simplest way to subtract a tuple by another tuple.

a = (1, 2, 3, 4)
b = (1, 2)

c = ()

for i in a:
    if i not in b:
        c = c + (i,)

print(c)  # (3, 4)

The trailing comma is basically optional but needed to append each value to the tuple in this case. A tuple with only one element is not a tuple but simply a value.

If tuple b has elements tuple a doesn't have, this code works well and the result is like the difference of sets.

a = (1, 2, 3, 4)
b = (1, 2, 5)

c = ()

for i in a:
    if i not in b:
        c = c + (i,)

print(c)  # (3, 4)

5 is in b but not in c.

Python Tuple

Python Tutorial