2

I know how to multiply the elements of a single tuple:

tup = (2,3)
tup[0]*tup[1]
6

My question is how do you multiply the elements of several tuples using a for loop?

example: How do I get x = (4,5,6) when x = ((2,2), (5,1), (3,2))?

4 Answers 4

5

Something like this:

tuple(a*b for a, b in x)
2

for tuples of any length, one line script:

>>> tpl = ((2,2), (5,1), (3,2,4))
>>> tuple(reduce(lambda x, y: x*y, tp) for tp in tpl)
(4, 5, 24)
>>> 
1

If you want to use it on tuples of any length:

tuple(product(myTuple) for myTuple in ((2,2), (5,1), (3,2)))

where

def product(cont):
  base = 1
  for e in cont:
    base *= e
  return base
1
x = ((2, 2), (5, 1), (3, 2))
y = ((2, 3), (2, 3, 5), (2, 3, 5, 7))

def multiply_the_elements_of_several_tuples_using_a_for_loop(X):
    tuple_of_products = []

    for x in X:
        product = 1

        for element in x:
            product *= element

        tuple_of_products.append(product)

    return tuple(tuple_of_products)

print(multiply_the_elements_of_several_tuples_using_a_for_loop(x))
print(multiply_the_elements_of_several_tuples_using_a_for_loop(y))

Output:

(4, 5, 6)
(6, 30, 210)
1
  • Plus for handling any length inner tuple Nov 12, 2011 at 17:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.