DEV Community

sumandari
sumandari

Posted on

sum, max, min, and statistics method with list and generator in python

If you have data both in list or generator, you can simplify the calculation by using sum(), max() and min() built-in functions.

>>> mylist = [_ * 3 for _ in range(10)]
>>> mylist
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
>>> max(mylist)
27
>>> min(mylist)
0
>>> sum(mylist)
135
Enter fullscreen mode Exit fullscreen mode

if you use a generator, you need to re-create the iterated objects by re-defined the generator objects.

>>> mygenerator = (_ * 3 for _ in range(10))
>>> mygenerator
<generator object <genexpr> at 0x1035170d0>
>>> max(mygenerator)
27
>>> min(mygenerator) # all objects have been iterated in the previous calculation max
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: min() arg is an empty sequence
>>> mygenerator = (_ * 3 for _ in range(10))
>>> min(mygenerator)
0
>>> sum(_ * 3 for _ in range(10))
135
>>> 
Enter fullscreen mode Exit fullscreen mode

and you can also use methods in statistics module:

>>> import statistics
>>> statistics.median_low(_ * 3 for _ in range(10))
12
>>> statistics.median_high(_ * 3 for _ in range(10))
15
>>> statistics.median(_ * 3 for _ in range(10))
13.5
>>> statistics.mean(_ * 3 for _ in range(10))
13.5
>>> statistics.mean(mylist)
13.5
>>> statistics.median_low(mylist)
12
Enter fullscreen mode Exit fullscreen mode

see all statistics methods at https://docs.python.org/3.9/library/statistics.html

read more about generator at https://wiki.python.org/moin/Generators

Top comments (0)