Pairwise Addition in Tuples in Python

PythonServer Side ProgrammingProgramming

If it is required to perform pairwise addition in tuples, then the 'zip' method, the 'tuple' method and a generator expression can be used.

The zip method takes iterables, aggregates them into a tuple, and returns it as the result.

Generator is a simple way of creating iterators. It automatically implements a class with '__iter__()' and '__next__()' methods and keeps track of the internal states, as well as raises 'StopIteration' exception when no values are present that could be returned.

The 'tuple' method converts a given iterable into tuple data type.

Below is a demonstration of the same −

Example

Live Demo

my_tuple = ( 67, 45, 34, 56, 99, 123, 0, 56)

print ("The tuple is : " )
print(my_tuple)

my_result = tuple(i + j for i, j in zip(my_tuple, my_tuple[1:]))

print ("The tuple after addition is : " )
print(my_result)

Output

The tuple is :
(67, 45, 34, 56, 99, 123, 0, 56)
The tuple after addition is :
(112, 79, 90, 155, 222, 123, 56)

Explanation

  • A tuple is created, and is displayed on the console.
  • The tuple and the same tuple excluding the first element is zipped, using the 'zip' method and is iterated over, using generator expression.
  • This is converted into a tuple, and this data is assigned to a variable.
  • This variable is displayed as the output on the console.
raja
Published on 11-Mar-2021 09:14:58
Advertisements