How do you sum all the values of the vector in Python?

Asked

Viewed 49 times

0

How can I sum all the values? Should I use an array (list) to store the values.

valores = []

for i in range(1,11):
    valores.append(input('Informe o {}º valor: '.format(i)))
  • Plinio, if you ever edit the question, add the relevant information in the body, not in the title. :)

  • Thanks for the tip! , I’m sorry, it’s just that I’m new here

2 answers

1


Once you have a numerical list, you can use the built-in function sum to add the elements. For example:

total = sum([1, 2, 3])
print(total) # 6

However, note that in your code, you are creating a list in which each member has the type str (returned by function input). Therefore, before adding members to the list, you must convert them to the appropriate type:

valores = []

for i in range(1, 11):
    valores.append(int(input('Informe o {}º valor: '.format(i))))

print(sum(valores))

Note that now, before adding to the list, we use int to convert the given value to the correct type (in this case it will be converted to an integer type). You could use float if floating point values were admissible.

Do not forget that int and float can launch a ValueError if the argument passed is invalid.

Some people may prefer to use a comprehensilist on for that kind of thing:

valores = [int(input(f"Informe o {i}º valor: ")) for i in range(1, 11)]
print(sum(valores))
  • 1

    Thank you very much man, you helped me a lot here!

0

from functools import reduce

valores = []

for i in range(1, 11):
    valores.append(int(input(f'Informe o {i}º valor: ')))

An alternative way is to use the function reduce. It aggregates the values in a single output.

reduce(lambda x, y : x + y, valores)

Browser other questions tagged

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