Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to calculate the sum of a list without creating the whole list first?

Usually we have to (1) declare a list (2) calculate a sum of this list using sum()

But now I wish to specify a list start with 1 and interval 4, 100 elements, like this:

[1,5,9,13,17,21,25,29,33,37,…]

I don’t want to envolve mathematical formula, so

(1) How to get the sum without even declaring this list?

(2) How to quickly get sum from 101st element to 200th element of this list?

like image 923
Troskyvs Avatar asked Mar 09 '23 23:03

Troskyvs


1 Answers

Simply use itertools.count to get a counter and itertools.islice to get the required number of elements (you can iterate these instances but they don't create a list!):

>>> from  itertools import count, islice
>>> sum(islice(count(1, step=4), 100))  # get the first 100 elements and sum them
19900

The islice also supports start/stop:

>>> sum(islice(count(1, step=4), 101, 200))  # 101st element to 200th
59499
like image 163
MSeifert Avatar answered Apr 27 '23 00:04

MSeifert