Reputation: 75
I'd like to know if there's a bult-in function in Python to add the elements of a list relative to a specific index. Let me explain. Say I have a list list = [1,2,3,4,5]
. I want to be able to add the numbers of lets say list[0:2]
. In this case the answer would be 6.
I know for a fact that I could do it with a simple loop but I would prefer a one liner, if possible.
Anyway, thanks in advance!
Upvotes: 0
Views: 90
Reputation: 44828
Just sum(your_list[0:2])
. This is easy and very fast. BTW, avoid calling your list list
because it will shadow the built-in list
function.
Upvotes: 2