1

I know sum(list) works to add ALL the elements in a list, but it doesn't allow you to select a range.

ex:

l = [11, 22, 33, 44, 55, 66, 77]    
x = 4

In this case I want to add l[0 : 4] together.

I know I can do:

short_l = l[0 : x]
sum(short_l)

But is there a function that allows me to select the range of elements within a list to add together?

Gronk
  • 381
  • 1
  • 3
  • 12

3 Answers3

1

You can use the builtin slice function to get the range of items, like this

l, x = [11, 22, 33, 44, 55, 66, 77], 4
print(sum(l[slice(0, 4)]))
# 110

The parameters to slice are the same as the slicing syntax.

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
1

If you don't want to create a sublist, you can use itertools.islice:

>>> import itertools
>>> l = [11, 22, 33, 44, 55, 66, 77]
>>> sum(itertools.islice(l, 0, 4))
110
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Is there any way in which this is better than: `sum(l[slice(0,4)])` ? – Gronk Mar 05 '14 at 06:41
  • 1
    @Gronk, `l[slice(0,4)]` returns a sublist, while `itertools.islice(l, 0, 4)` returns a iterator. In case the sublist is huge, `itertools.islice` is more memory-efficient. But for small sublist, the it will not make much difference. – falsetru Mar 05 '14 at 06:41
  • @Gronk, `l[slice(0,4)]` is a just another way of expressing `l[0:4]`. (`l[0:4] == l[slice(0,4)]`) – falsetru Mar 05 '14 at 06:43
  • The list grows up to over 12,000 elements so this is good to know. – Gronk Mar 05 '14 at 06:50
  • 1
    @Gronk: Use `islice` if the slice is huge (12000 items is only 50 to 100 KiB -- a drop in the bucket), or if you're creating thousands or millions of slices that coexist on the heap. Otherwise using a regular slice will usually perform better. – Eryk Sun Mar 05 '14 at 11:36
0

Why do you need a new function anyways? Just do sum(l[0:x]). If you really want a function, you can define one yourself:

def sum_range(lst, end, start=0):
    return(sum(lst[start : end + 1]))

which adds from index start to end including end. And start is default to index 0 if not specified.

Xufeng
  • 6,452
  • 8
  • 24
  • 30