0

For example, this runs in Python:

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

and prints:

(1,2,3,1,4,5)

but I get why it won't allow for something like subtracting (a-b). How would I be able to I guess 'remove' an item from a tuple although tuples aren't mutable.:

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

so it would return:

(2,3)
  • 3
    Because it's unclear what the general definition of "subtracting a tuple" should do…?! – deceze Feb 10 '20 at 10:55
  • 1
    For this functionality, you might want to use sets - see [here](https://stackoverflow.com/q/60099992/12366110). Note that sets only store unique items, so when subtracting sets, there is no ambiguity as to which elements to remove. – CDJB Feb 10 '20 at 10:56
  • 2
    You cannot mutate a `tuple`. So, create a new `tuple` as `c=tuple(i for i in a if i not in b)` and `c=(2,3)`. Note if `a=(1,2,3,1)` and `b=(1,)`, `c` will be `(2,3)` if you use above method. And it's still unclear what do you mean by *subtracting two tuples*. if you want to implement the mentioned behaviour use `set` . – Ch3steR Feb 10 '20 at 11:00
  • 1
    Non-mutability is not an issue, since (as OP points out) `+` works (by creating a new tuple). The bigger issue is, as deceze says, that it is not clear what it should mean, whereas concatenation is well defined. For example, what should be the result of `(1, 4, 1, 1, 2, 3, 2) - (1, 1, 2)` be? `(1, 4, 3, 2)` by taking out the subsequence? `(4, 3)` by taking out each matching element? `(4, 1, 3, 2)` by taking the first `1` and the first two `2`? – Amadan Feb 10 '20 at 11:05
  • 1
    @Amadan Yet others may want to define it as vector arithmetic, e.g. `(2, 3, 4) - (1, 1, 1)` results in `(1, 2, 3)`… – deceze Feb 10 '20 at 11:08
  • 1
    @Amadan Spot on. I wanted to explain the same through my comment but maybe I was unclear. Even if op used the approach I mentioned It wouldn't make sense as he can use `set` for that purpose which is more efficient. – Ch3steR Feb 10 '20 at 11:09
  • 2
    @deceze I wasn't going to go there, because then `(2, 3, 4) + (1, 1, 1)` would reasonably be expected to produce `(3, 4, 5)`. :P – Amadan Feb 10 '20 at 11:09

0 Answers0