Given, a list of tuples, the task is to multiply the elements of the tuple and return 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 elements of a tuple. Let’s see a couple of them.
# Method 1: Using Iteration
This is the most naive method to achieve a solution to this task. In this, we iterate over the whole list of tuples and multiply the elements in each tuple to get the list of elements.
# Python code to convert list of tuple into list of elements # formed by multiplying elements of tuple. # Input list initialisation Input = [( 2 , 3 ), ( 4 , 5 ), ( 6 , 7 ), ( 2 , 8 )] # Output list initialisation Output = [] # Iteration to multiply element and append multiplied element in # new list for elem in Input : temp = elem[ 0 ] * elem[ 1 ] Output.append(temp) # printing output print ( "The original list of tuple is " ) print ( Input ) print ( "\nThe answer is" ) print (Output) |
Output:
The original list of tuple is [(2, 3), (4, 5), (6, 7), (2, 8)] The answer is [6, 20, 42, 16]
# Method 2: Using list comprehension
This is the one-liner approach to achieve the solution to this task.
# Python code to convert list of tuple into list of elements # formed by multiplying elements of tuple. # Input list initialisation Input = [( 2 , 3 ), ( 4 , 5 ), ( 6 , 7 ), ( 2 , 8 )] # Iteration to multiply element and append multiplied element in # new list Output = [(x * y) for x, y in Input ] # printing output print ( "The original list of tuple is " ) print ( Input ) print ( "\nThe answer is" ) print (Output) |
Output:
The original list of tuple is [(2, 3), (4, 5), (6, 7), (2, 8)] The answer is [6, 20, 42, 16]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.