
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Pairwise Addition in Tuples in Python
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
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.
- Related Articles
- Addition of tuples in Python
- Addition in Nested Tuples in Python
- Combining tuples in list of tuples in Python
- Count tuples occurrence in list of tuples in Python
- Program to swap string characters pairwise in Python
- Updating Tuples in Python
- Compare tuples in Python
- How to Concatenate tuples to nested tuples in Python
- Remove duplicate tuples from list of tuples in Python
- Program to make pairwise adjacent sums small in Python
- Check if Queue Elements are pairwise consecutive in Python
- Basic Tuples Operations in Python
- Remove matching tuples in Python
- Accessing Values of Tuples in Python
- What are "named tuples" in Python?

Advertisements