Open In App

Python | Multiply Adjacent elements

Last Updated : 23 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with data, we can have a problem in which we need to find cumulative result. This can be of any type, product or summation. Here we are gonna discuss about adjacent element multiplication. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using zip() + generator expression + tuple() The combination of above functionalities can be used to perform this task. In this, we use generator expression to provide multiplication logic and simultaneous element pairing is done by zip(). The result is converted to tuple form using tuple(). 

Python3




# Python3 code to demonstrate working of
# Adjacent element multiplication
# using zip() + generator expression + tuple
 
# initialize tuple
test_tup = (1, 5, 7, 8, 10)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# Adjacent element multiplication
# using zip() + generator expression + tuple
res = tuple(i * j for i, j in zip(test_tup, test_tup[1:]))
 
# printing result
print("Resultant tuple after multiplication : " + str(res))


Output

The original tuple : (1, 5, 7, 8, 10)
Resultant tuple after multiplication : (5, 35, 56, 80)

  Method #2 : Using tuple() + map() + lambda The combination of above functions can also help to perform this task. In this, we perform multiplication and binding logic using lambda function. The map() is used to iterate to each element and at end result is converted by tuple(). 

Python3




# Python3 code to demonstrate working of
# Adjacent element multiplication
# using tuple() + map() + lambda
 
# initialize tuple
test_tup = (1, 5, 7, 8, 10)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# Adjacent element multiplication
# using tuple() + map() + lambda
res = tuple(map(lambda i, j : i * j, test_tup[1:], test_tup[:-1]))
 
# printing result
print("Resultant tuple after multiplication : " + str(res))


Output

The original tuple : (1, 5, 7, 8, 10)
Resultant tuple after multiplication : (5, 35, 56, 80)

Method #4: Using numpy

Note: Install numpy module using command “pip install numpy”

The numpy library in Python provides a function called numpy.multiply() which can be used to perform element-wise multiplication.

Python3




import numpy as np
 
# initialize tuple
test_tup = (1, 5, 7, 8, 10)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# Adjacent element multiplication using numpy
res = np.multiply(test_tup[1:], test_tup[:-1])
 
# printing result
print("Resultant tuple after multiplication : " + str(tuple(res)))
 
#This code is contributed by Edula Vinay Kumar Reddy


Output:

The original tuple : (1, 5, 7, 8, 10)
Resultant tuple after multiplication : (5, 35, 56, 80)

Time complexity: O(n) where n is the size of the tuple. 
Auxiliary Space: O(n)

Method 4: Using a for loop

Step-by-step approach:

  • Initialize the input tuple test_tup.
  • Print the original tuple.
  • Initialize an empty list res to store the result.
  • Iterate over the input tuple using a for loop.
  • Multiply the current element with its adjacent element and append the result to res.
  • Convert res to a tuple using the tuple() function.
  • Print the resultant tuple

Python3




# Python3 code to demonstrate working of
# Adjacent element multiplication
# using for loop
 
# initialize tuple
test_tup = (1, 5, 7, 8, 10)
 
# printing original tuple
print("The original tuple : " + str(test_tup))
 
# initialize an empty list to store the result
res = []
 
# iterate over the tuple and perform multiplication of adjacent elements
for i in range(len(test_tup) - 1):
    res.append(test_tup[i] * test_tup[i+1])
 
# convert the list to a tuple
res = tuple(res)
 
# printing result
print("Resultant tuple after multiplication : " + str(res))


Output

The original tuple : (1, 5, 7, 8, 10)
Resultant tuple after multiplication : (5, 35, 56, 80)

Time complexity: O(n), where n is the length of the input tuple.
Auxiliary space: O(n), to store the res list.



Similar Reads

Python | Multiply elements of Tuple
Given, a list of tuples, the task is to multiply the elements of the tuple and return a list of the multiplied elements. Examples: Input: [(2, 3), (4, 5), (6, 7), (2, 8)] Output: [6, 20, 42, 16] Input: [(11, 22), (33, 55), (55, 77), (11, 44)] Output: [242, 1815, 4235, 484] There are multiple ways to multiply the elements of a tuple. Let's see a cou
4 min read
Python - Multiply Consecutive elements in list
While working with python, we usually come by many problems that we need to solve in day-day and in development. Specially in development, small tasks of python are desired to be performed in just one line. We discuss some ways to compute a list consisting of elements that are successive product in the list. Method #1 : Using list comprehension Nai
7 min read
Python program to multiply two matrices
Given two matrix the task is that we will have to create a program to multiply two matrices in python. Examples: Input : X = [[1, 7, 3], [3, 5, 6], [6, 8, 9]] Y = [[1, 1, 1, 2], [6, 7, 3, 0], [4, 5, 9, 1]] Output : [55, 65, 49, 5] [57, 68, 72, 12] [90, 107, 111, 21]Recommended: Please try your approach on {IDE} first, before moving on to the soluti
4 min read
Python | Pandas Series.multiply()
Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.multiply() function perform the multiplication of series and other, element-wis
2 min read
Differentiate Hermite series and multiply each differentiation by scalar using NumPy in Python
In this article, we will see how to differentiate the Hermite series and multiply each differentiation by a scalar in python. hermite.hermder method The hermite.hermder() is used to differentiate the Hermite series which is available in the NumPy module. We can pass the following parameters, the first parameter will be the c, which is an array of H
2 min read
numpy.defchararray.multiply() in Python
numpy.core.defchararray.multiply(arr, n): Concatenates strings 'n' times element-wise. Parameters: arr : array-like or string. n : [array-like] no. of times we want to concatenate. Returns : Concatenated String 'n' times element-wise. Code #1: # Python Program illustrating # numpy.char.multiply() method import numpy as np arr1 = ['eAAAa', 'ttttds',
1 min read
numpy.multiply() in Python
numpy.multiply() function is used when we want to compute the multiplication of two array. It returns the product of arr1 and arr2, element-wise. Syntax : numpy.multiply(arr1, arr2, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj], ufunc 'multiply') Parameters : arr1: [array_like or scalar]1st
3 min read
Python | Multiply each element in a sublist by its index
Given a list of lists, the task is to multiply each element in a sublist by its index and return a summed list. Given below are a few methods to solve the problem. Method #1: Using Naive Method C/C++ Code # Python3 code to demonstrate # to multiply numbers with position # and add them to return num import numpy as np # initialising list ini_list =
4 min read
Python PIL | ImageChops.multiply() method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageChops module contains a number of arithmetical image operations, called channel operations (“chops”). These can be used for various purposes, including special effects, image compositions, algorithmic painting, and more. PIL.ImageChops.
1 min read
Python | Repeat and Multiply list extension
Sometimes, while working with Python list, we can have a problem in which we need to extend a list in a very customized way. We may have to repeat contents of list and while doing that, each time new list must be a multiple of original list. This incremental expansion has applications in many domains. Let's discuss a way in which this task can be p
6 min read
Practice Tags :
three90RightbarBannerImg