Borislav Hadzhiev
Last updated: Jul 9, 2022
Photo from Unsplash
To multiply each element in a tuple by a number:
tuple()
class to convert the generator object to a tuple.import math my_tuple = (2, 4, 6) # ✅ multiply each element in tuple by a number result = tuple(num * 10 for num in my_tuple) print(result) # 👉️ (20, 40, 60) # --------------------------------- # ✅ multiply all elements in a tuple result_2 = math.prod(my_tuple) print(result_2) # 👉️ 48
We used a generator expression to iterate over the tuple.
On each iteration, we multiply the current number by a different number and return the result.
The last step is to pass the generator
object to the tuple()
class.
The tuple class
takes an iterable and returns a tuple
object.
You might also see examples online that use a list comprehension instead of a generator expression.
my_tuple = (2, 4, 6) result = tuple([num * 10 for num in my_tuple]) print(result) # 👉️ (20, 40, 60)
List comprehensions are also used to perform some operation for every element, or select a subset of elements that meet a condition.
If you need to multiply all of the elements in a tuple, use the math.prod()
function.
import math my_tuple = (2, 4, 6) result_2 = math.prod(my_tuple) print(result_2) # 👉️ 48
The math.prod method calculates the product of all the elements in the provided iterable.
import math my_tuple = (5, 5, 5) result = math.prod(my_tuple) print(result) # 👉️ 125
The method takes the following 2 arguments:
Name | Description |
---|---|
iterable | An iterable whose elements to calculate the product of |
start | The start value for the product (defaults to 1 ) |
If the iterable is empty, the start
value is returned.