Multiplying terms from the list

Asked

Viewed 9,053 times

2

I want to print the multiplication of the terms and I would like to know if there is a function capable of doing this for me in the Python language:

lista = []

con = 0

while(con<5):
    n = int(input('insira um número inteiro'))

   con = con + 1

   lista.append(n)

   print('lista criada=',lis
ta)

   print('soma das listas=',sum(lista))

3 answers

7

There’s no proper function for it, but there are ways that make it possible for you not to have to do everything by hand. One of the simplest ways is to combine the use of functions functools.reduce with operator.mul:

from functools import reduce
from operator import mul

lista = [1, 2, 3, 4, 5]
produto = reduce(mul, lista, 1)
print(produto)  # 120

Or, doing it iteratively:

produto = 1
for numero in lista:
    produto *= numero
print(produto)  # 120

3


1

If you are using the Python 3.8 or higher, you can make use of the method Prod library Math. This method is used to calculate the product of the elements of an eternal.

This way the code can be written...

from math import prod

i = 1
lista = []
while i < 5:
    lista.append(int(input(f'Insira o {i}º número inteiro: ')))
    i += 1

print(f'O produto é: {prod(lista)}')

...or...

from math import prod

lista = list()
for i in range(1, 5):
    lista.append(int(input(f'Insira o {i}º número inteiro: ')))

print(f'O produto é: {prod(lista)}')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.