Addition of two equal-length tuples adds each element from one tuple to the element at the same index in another tuple.
For example, the addition of (1, 2, 3, 4)
and (1, 2, 2, 1)
results in (2, 4, 5, 5)
.
Here are the ways using you can easily add tuples in Python.
Use map() to Add Tuples
Call the map(function, tuple1, tuple2)
function with tuple1
and tuple2
as iterables and lambda x, y: x+y
as the function
parameter. This will return the sum of elements as a list, so call the tuple()
constructor on the result to convert the list into a tuple object.
tuple(map(lambda x, y: x+y, tuple1, tuple2))
You can make this more compact by using the operator.add
function of the operator module instead of the lambda function.
import operator
tuple(map(operator.add, tuple1, tuple2))
Another way to add tuples using the map function is to pair each of the same index elements of the tuples as items into a list using the zip(tuple1, tuple2)
function and call the map(sum, iterable)
with sum
as the function and result of the zip(tuple1, tuple2)
as iterable
.
tuple(map(sum, zip(tuple1, tuple2)))
Use Generator Comprehension to Add Tuples
Call the tuple()
constructor with (x+y for x, y zip(tuple1, tuple2))
as the generator comprehension to add two tuples in Python.
tuple(x+y for x, y zip(tuple1, tuple2))