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
Multiply Adjacent elements in Python
When it is required to multiply adjacent elements, the zip() method, the tuple() method, and generator expressions can be used.
The zip() method takes iterables, aggregates them into a tuple, and returns it as the result. Generator expressions provide a simple way of creating iterators that automatically implement __iter__() and __next__() methods.
Basic Example
Here's how to multiply adjacent elements in a tuple ?
my_tuple = (7, 8, 0, 3, 45, 3, 2, 22)
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 multiplication is:")
print(my_result)
The tuple is: (7, 8, 0, 3, 45, 3, 2, 22) The tuple after multiplication is: (56, 0, 0, 135, 135, 6, 44)
How It Works
The solution uses zip(my_tuple, my_tuple[1:]) to pair each element with its next neighbor:
-
my_tuple[1:]creates a slice starting from the second element -
zip()pairs corresponding elements: (7,8), (8,0), (0,3), etc. - Generator expression multiplies each pair: 7×8=56, 8×0=0, 0×3=0
-
tuple()converts the generator result back to a tuple
Working with Lists
The same approach works with lists ?
numbers = [2, 3, 4, 5, 6]
result = [i * j for i, j in zip(numbers, numbers[1:])]
print("Original list:", numbers)
print("Adjacent products:", result)
Original list: [2, 3, 4, 5, 6] Adjacent products: [6, 12, 20, 30]
Using a Function
For reusability, create a function ?
def multiply_adjacent(sequence):
return [i * j for i, j in zip(sequence, sequence[1:])]
# Test with different sequences
data1 = [1, 2, 3, 4, 5]
data2 = (10, 20, 30)
print("List result:", multiply_adjacent(data1))
print("Tuple result:", multiply_adjacent(data2))
List result: [6, 12, 20, 30] Tuple result: [200, 600]
Conclusion
Use zip(sequence, sequence[1:]) with generator expressions to multiply adjacent elements efficiently. This approach works with any sequence type and produces n-1 results from n elements.
