Multiply Adjacent elements in Python


When it is required to multiply adjacent elements, the 'zip' method, the 'tuple' method, and the 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.

Below is a demonstration of the same −

Example

Live Demo

my_tuple_1 = (7, 8, 0 ,3, 45, 3, 2, 22)

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

my_result = tuple(i * j for i, j in zip(my_tuple_1, my_tuple_1[1:]))

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

Output

The tuple is :
(7, 8, 0, 3, 45, 3, 2, 22)
The tuple after multiplication is :
(56, 0, 0, 135, 135, 6, 44)

Explanation

  • A tuple is defined, and is displayed on the console.
  • It is zipped, along with the same tuple by leaving out the first element, and is iterated over, and the corresponding elements in the tuple are multipled.
  • This result is assigned to a value.
  • It is displayed as output on the console.

Updated on: 11-Mar-2021

482 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements