0

E.g., why can't I do:

(0,1) + (2,2)

and get:

(2,3)

as a result?

jps
  • 20,041
  • 15
  • 75
  • 79
capybaralet
  • 1,757
  • 3
  • 21
  • 31

5 Answers5

2

Because the + operator is used to make a new tuple that is the combination of two other tuples. That is just how Python was designed.

To do what you want, you can use zip and a generator expression:

>>> t1 = (0,1)
>>> t2 = (2,2)
>>> tuple(x + y for x, y in zip(t1, t2))
(2, 3)
>>>
1

Its because of you add tow tuple and + operation for tuples concatenate them ! you can use map and zip functions for that :

>>> map(sum,zip((0,1),(2,2)))
[2, 3]

or use a generator :

>>> tuple(i+j for i,j in zip((0,1),(2,2)))
(2, 3)

and a better way with operator.add:

>>> from operator import add
>>> map(add,(0,1),(2,2))
[2, 3]
Mazdak
  • 105,000
  • 18
  • 159
  • 188
1

'+' operator concatenate tuples . if you want to sum tuples item you can use:

tuple(sum(x) for x in zip((0,1),(2,2)))

or

tuple(map(sum,zip((0,1),(2,2))))
Hasan Ramezani
  • 5,004
  • 24
  • 30
0

Since Python thinks of tuples as lists that are immutable, adding two tuples is just like adding two lists. So, just as adding two lists will concatenate them:

>>> [1, 2] + [3, 4]
[1, 2, 3, 4]

adding two tuples will also concatenate them:

>>> (1, 2) + (3, 4)
(1, 2, 3, 4)

You can create a new tuple that consists of the sum of each pair with a few of Python's built-in functions:

>>> tuple(map(sum, zip((0, 1), (2, 2))))
(2, 3)

This works by using zip() on the two tuples to make a list of pairs:

>>> zip((0, 1), (2, 2))
[(0, 2), (1, 2)]

And using map() to apply sum() on each element of that list, to get a list of sums:

>>> map(sum, zip((0, 1), (2, 2)))
[2, 3]

And, finally, using tuple() to turn that from a list into a tuple.

APerson
  • 8,140
  • 8
  • 35
  • 49
0

Element-wise addition is a more specialized operation than concatenation. Fewer tuples could be added together: what would ('a','b') + (1,2,) equal? Or ('a', 'b') + (1,2,3) for that matter?

Since concatenation is arguably the more commonly desired operation, and importantly, well defined for all tuples, it makes sense that addition of tuples performs concatenation.

unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677