Python | Multiple adjacent elements

Python Methods and Functions

Method # 1: Using zip () + expression generator + tuple()
A combination of the above functions can be used to completing this task. In this, we use a generator expression to provide the logic for the multiplication and concurrent connection of the elements is done using zip () . The result is converted to the form tuple () using tuple () .

# Python3 demo code work
# Multiply adjacent elements
# using zip () + expression generator + tuple

 
# initialize tuple

test_tup = ( 1 , 5 , 7 , 8 , 10 )

 
# print ori ginal tuple

print ( "The original tuple: " + str (test_tup))

 
# Multiply adjacent elements
# using zip () + expression generator + tuple

res = tuple (i * j for i, j in zip (test_tup, test_tup [ 1 :]))

 
# print 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
A combination of the above functions can also help accomplish this task. In this, we execute the logic of multiplication and binding using a lambda function.  map () is used to iterate over each element and finally converted with tuple () .

# Python3 code to demonstrate how it works
# Multiply adjacent elements
# using tuple () + map () + lambda

 
# initialize the tuple

test_tup = ( 1 , 5 , 7 , 8 , 10 )

 
# print the original tuple

print ( "The original tuple:" + str ( test_tup))

 
# Multiply adjacent elements
# using tuple () + map () + lambda

res = tuple ( map ( lambda i, j: i * j, test_tup [ 1 :], test_tup [: - 1 ]))

 
# print result

print ( "Resultant tuple after multiplication:" + str (res))

Exit:

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




Get Solution for free from DataCamp guru