Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Pairwise Addition in Tuples in Python
Pairwise addition in tuples means adding each element with its next adjacent element. Python provides an elegant solution using zip(), generator expressions, and the tuple() constructor.
The zip() method takes iterables, pairs their elements together, and returns an iterator of tuples. A generator expression provides memory-efficient iteration, while tuple() converts the result into a tuple.
Basic Example
Here's how to perform pairwise addition on a tuple ?
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 pairwise addition is:")
print(my_result)
The tuple is: (67, 45, 34, 56, 99, 123, 0, 56) The tuple after pairwise addition is: (112, 79, 90, 155, 222, 123, 56)
How It Works
The solution works by creating two sequences ?
numbers = (10, 20, 30, 40)
# Original tuple: (10, 20, 30, 40)
print("Original tuple:", numbers)
# Sliced tuple: (20, 30, 40)
print("Sliced tuple:", numbers[1:])
# Zip pairs them: (10,20), (20,30), (30,40)
pairs = list(zip(numbers, numbers[1:]))
print("Zipped pairs:", pairs)
# Add each pair: 30, 50, 70
result = tuple(i + j for i, j in zip(numbers, numbers[1:]))
print("Pairwise sum:", result)
Original tuple: (10, 20, 30, 40) Sliced tuple: (20, 30, 40) Zipped pairs: [(10, 20), (20, 30), (30, 40)] Pairwise sum: (30, 50, 70)
Alternative Approach Using List Comprehension
You can achieve the same result using list comprehension with indexing ?
my_tuple = (5, 15, 25, 35, 45)
# Using list comprehension with indexing
result = tuple(my_tuple[i] + my_tuple[i+1] for i in range(len(my_tuple)-1))
print("Original tuple:", my_tuple)
print("Pairwise addition:", result)
Original tuple: (5, 15, 25, 35, 45) Pairwise addition: (20, 40, 60, 80)
Handling Empty and Single Element Tuples
Consider edge cases where the tuple has fewer than two elements ?
# Empty tuple
empty_tuple = ()
result1 = tuple(i + j for i, j in zip(empty_tuple, empty_tuple[1:]))
print("Empty tuple result:", result1)
# Single element tuple
single_tuple = (42,)
result2 = tuple(i + j for i, j in zip(single_tuple, single_tuple[1:]))
print("Single element result:", result2)
# Two elements
two_elements = (10, 20)
result3 = tuple(i + j for i, j in zip(two_elements, two_elements[1:]))
print("Two elements result:", result3)
Empty tuple result: () Single element result: () Two elements result: (30,)
Conclusion
Pairwise addition in tuples is efficiently accomplished using zip() with tuple slicing and generator expressions. The zip(my_tuple, my_tuple[1:]) pattern pairs adjacent elements for mathematical operations.
