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.
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.
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.
You can directly enter duplicate items in a Python tuple as it doesn't behave like a set(which takes only unique items).
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.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With