Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Values From Tuples of Same Length

Tags:

In a graphical program I'm writing using pygame I use a tuple representing a coordinate like this: (50, 50).

Sometimes, I call a function which returns another tuple such as (3, -5), which represents the change in coordinate.

What is the best way to add the change value to the coordinate value. It would be nice if I could do something like coordinate += change, but it appears that would simply concatenate the two tuples to something like (50, 50, 3, -5). Rather than adding the 1st value to the 1st value and the 2nd to the 2nd, and returning a resulting tuple.

Until now I've been using this rather tiresome method: coord = (coord[0] + change[0], coord[1] + change[1])

What is a better, more concise method to add together the values of two tuples of the same length. It seems especially important to know how to do it if the tuples are of an arbitrary length or a particularly long length that would make the previous method even more tiresome.

like image 386
Keegan Jay Avatar asked Jul 23 '09 05:07

Keegan Jay


People also ask

How do you add tuple values together?

Concatenating and Multiplying TuplesConcatenation is done with the + operator, and multiplication is done with the * operator. Because the + operator can concatenate, it can be used to combine tuples to form a new tuple, though it cannot modify an existing tuple. The * operator can be used to multiply tuples.

Can we add values in tuples?

In Python, since tuple is immutable, you cannot update it, i.e., you cannot add, change, or remove items (elements) in tuple . tuple represents data that you don't need to update, so you should use list rather than tuple if you need to update it.

Can we add repeated values to the tuples in Python?

You can directly enter duplicate items in a Python tuple as it doesn't behave like a set(which takes only unique items).

How do you add two tuples together?

When it is required to concatenate multiple tuples, the '+' operator can be used. A tuple is an immutable data type. It means, values once defined can't be changed by accessing their index elements.


2 Answers

Well, one way would be

coord = tuple(sum(x) for x in zip(coord, change)) 

If you are doing a lot of math, you may want to investigate using NumPy, which has much more powerful array support and better performance.

like image 107
John Y Avatar answered Oct 03 '22 19:10

John Y


List comprehension is probably more readable, but here's another way:

>>> a = (1,2) >>> b = (3,4) >>> tuple(map(sum,zip(a,b))) (4,6) 
like image 23
Kenan Banks Avatar answered Oct 03 '22 21:10

Kenan Banks