Eg: list = 1, 2, 3… 10
I am trying to solve a question in my course in as simple a way as possible. Sorry if there is already an answer to this question. I couldn't find anything.
Eg: list = 1, 2, 3… 10
I am trying to solve a question in my course in as simple a way as possible. Sorry if there is already an answer to this question. I couldn't find anything.
if a
is the list
the you can do:
print sum(a[:3])
You can go through the sum() function of python.
Moreover, a[:3]
is a slicing operation.
Just use slicing:
mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = sum(mylist[:3])
Here, you can easily change 3
to some other number.
See:
The sum function sums numbers in an iterable and is built into Python.
Thus for your situation you can just slice the list and use it.
numbers = [2.5, 3, 4, -5]
numbersSum = sum(numbers[:3])
print(numbersSum)
result is 2.5+3+4=9.5