-2

If we have a list like this list=[1,2,3] and want to add all of the elements up like this 1+2+3 and get the result. How do we do that?

  • 1
    `print(sum(your_list))` should do. – kiner_shah Nov 16 '21 at 07:01
  • 2
    Do not use `list`. Rename it to, say `lst`, and try `sum(lst)`. – j1-lee Nov 16 '21 at 07:01
  • 3
    Duplicate: [Summing elements in a list](https://stackoverflow.com/questions/11344827/summing-elements-in-a-list) – SiHa Nov 16 '21 at 07:20
  • There is the builtin function `sum` which you can call directly on a list to get its sum. Or if you want to go back to basics and do things yourself for learning purposes, you can write a `for`-loop. However, never name your lists `list`. This is already the name of the class `list` which handles all lists, and shadowing that name can have unintended consequences. – Stef Nov 16 '21 at 09:41

1 Answers1

1

Shortest code:

lst = [1,2,3]
print(sum(lst))
Tom Epsilon
  • 188
  • 6