Python program to multiply adjacent elements of a tuple

In this program, we are given a tuple. We need to create a Python program to multiply adjacent elements of the tuple.
Submitted by Shivang Yadav, on December 28, 2021

Performing an inter-value operation on collections to extract some fruitful information is sometimes required in the program like in scoring systems and statistics programs. So, we must know ways to perform such tasks. Here, we will see a program in Python to multiply adjacent elements of a tuple.

Before going further with the problem, let's recap some basic topics that will help in understanding the solution.

Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.

Tuples in Python is a collection of items similar to list with the difference that it is ordered and immutable.

Example:

tuple = ("python", "includehelp", 43, 54.23)

Multiplying adjacent elements of a tuple

In this problem, we are given a tuple with integer elements. In our program, we need to create a tuple from the elements of the initial tuple where each tuple is the product of the element at that index and next index.

Input:
(5, 1, 8, 3, 7)

Output:
(5, 8, 24, 21)

To perform this task we will iterate the first tuple and find the product of the current element and its next. This can be done in multiple ways in Python.

Method 1:

One method to solve the problem is by zipping the current element and the next one for each element of the tuple. Then using the generator expression along with tuple method to create a tuple with the resulting values.

# Python program to multiply adjacent 
# elements of a tuple

# Initializing and printing tuple value
myTup = (5, 1, 8, 3, 7)
print("The elements of tuple : " + str(myTup))

# Multiplying adjacent elements of the tuple 
adjProd = tuple(val1 * val2 for val1, val2 in zip(myTup, myTup[1:]))
print("The multiplication values are " + str(adjProd))

Output:

The elements of tuple : (5, 1, 8, 3, 7)
The multiplication values are (5, 8, 24, 21)

Method 2:

Another method to solve the problem is by creating a map that uses a lambda function to multiply the current index element and the next index element of the tuple and then convert this map to a tuple.

# Python program to multiply adjacent 
# elements of a tuple

# Initializing and printing tuple value
myTup = (5, 1, 8, 3, 7)
print("The elements of tuple : " + str(myTup))

# Multiplying adjacent elements of the tuple 
adjProd = tuple(map(lambda val1, val2 : val1 * val2, myTup[1:], myTup[:-1]))

print("The multiplication values are " + str(adjProd))

Output:

The elements of tuple : (5, 1, 8, 3, 7)
The multiplication values are (5, 8, 24, 21)

Python Tuple Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.