Multiply each element in a tuple by a number in Python

avatar

Borislav Hadzhiev

Last updated: Jul 9, 2022

banner

Photo from Unsplash

Multiply each element in a tuple by a number in Python #

To multiply each element in a tuple by a number:

  1. Use a generator expression to iterate over the tuple.
  2. On each iteration, multiply the current tuple element by the number.
  3. Use the tuple() class to convert the generator object to a tuple.
main.py
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.

Generator expressions are used to perform some operation for every element, or select a subset of elements that meet a condition.

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.

main.py
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.

However, using a list comprehension is not necessary since we have to convert the list to a tuple anyway.

If you need to multiply all of the elements in a tuple, use the math.prod() function.

main.py
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.

main.py
import math my_tuple = (5, 5, 5) result = math.prod(my_tuple) print(result) # 👉️ 125

The method takes the following 2 arguments:

NameDescription
iterableAn iterable whose elements to calculate the product of
startThe start value for the product (defaults to 1)

If the iterable is empty, the start value is returned.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.