-1

Let's say a=(1,2) and b=(3,4) What should print(a+b) give?

I expect the output (4,6), but the actual output is(1,2,3,4)

  • it is already answered [here](https://stackoverflow.com/questions/497885/python-element-wise-tuple-operations-like-sum) – Majo_Jose Apr 17 '19 at 05:51
  • 1
    Because that's how Python defines what addition means for `tuple`s. If it behaved the way you want, then some other people would ask why `+` doesn't concatenate. There's no pleasing everyone. If you want to do element-wise addition, you'll need to do it yourself, possibly with your own class. – jamesdlin Apr 17 '19 at 05:55

2 Answers2

2

a and b are of tuple type. The + operator for tuples append the tuples to one another. To actually sum element-wise tuples, you need to do the following:

[sum(x) for x in zip(a,b)]

You can find more info here: https://stackoverflow.com/a/16548756/4949074

ggrelet
  • 1,071
  • 7
  • 22
1

Because it is a tuple type which is a sequence type for which the + operator does concatenation and not addition. If you want numeric vectors, look at, e.g., NumPy.

wilx
  • 17,697
  • 6
  • 59
  • 114