Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add with tuples

I have pseudo-code like this:

if( b < a)
   return (1,0)+foo(a-b,b)

I want to write it in python. But can python add tuples? What is the best way to code something like that?

like image 898
fpointbin Avatar asked Apr 09 '11 19:04

fpointbin


People also ask

How do you sum two tuples?

To add two tuples element-wise: Use the zip function to get an iterable of tuples with the corresponding items. Use a list comprehension to iterate over the iterable. On each iteration, pass the tuple to the sum() function.

How do you add numbers to tuples?

In summary, tuples can't be simply modified like lists because of their immutable nature. The most extensive way to append to a tuple is to convert the tuple into a list. If the only addition needed is either at the start or the end of the tuple, then simple concatenation + can be used.

Can we add an element in a tuple?

You can't add elements to a tuple because of their immutable property. There's no append() or extend() method for tuples, You can't remove elements from a tuple, also because of their immutability.


4 Answers

I'd go for

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

or, more naturally:

>>> numpy.array((1, 2)) + numpy.array((3, 4))
array([4, 6])
like image 162
Dmitry Zotikov Avatar answered Sep 28 '22 21:09

Dmitry Zotikov


Do you want to do element-wise addition, or to append the tuples? By default python does

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

You could define your own as:

def myadd(x,y):
     z = []
     for i in range(len(x)):
         z.append(x[i]+y[i])
     return tuple(z)

Also, as @delnan's comment makes it clear, this is better written as

def myadd(xs,ys):
     return tuple(x + y for x, y in izip(xs, ys))

or even more functionally:

myadd = lambda xs,ys: tuple(x + y for x, y in izip(xs, ys))

Then do

if( b < a) return myadd((1,0),foo(a-b,b))
like image 30
highBandWidth Avatar answered Sep 28 '22 21:09

highBandWidth


tuple(map(operator.add, a, b))

In contrast to the answer by highBandWidth, this approach requires that the tuples be of the same length in Python 2.7 or earlier, instead raising a TypeError. In Python 3, map is slightly different, so that the result is a tuple of sums with length equal to the shorter of a and b.

If you want the truncation behavior in Python 2, you can replace map with itertools.imap:

tuple(itertools.imap(operator.add, a, b))
like image 23
Michael J. Barber Avatar answered Sep 28 '22 21:09

Michael J. Barber


If you want + itself to act this way, you could subclass tuple and override the addition:

class mytup(tuple):
    def __add__(self, other):
        if len(self) != len(other):
             return NotImplemented # or raise an error, whatever you prefer
         else:
             return mytup(x+y for x,y in izip(self,other))

The same goes for __sub__, __mul__, __div__, __gt__ (elementwise >) etc. More information on these special operators can be found e.g. here (numeric operations) and here (comparisions)

You can still append tuples by calling the original tuple addition: tuple.__add__(a,b) instead of a+b. Or define an append() function in the new class to do this.

like image 22
Tobias Kienzler Avatar answered Sep 28 '22 19:09

Tobias Kienzler