[Tutor] methods versus functions (using lists as an example)

Lloyd Kvam pythonTutor at venix.com
Tue Oct 19 19:31:42 CEST 2004


Not contradicting you, but it goes beyond lists and tuples.  Don't
forget about generators.

>>> def evens(limit=10):
...     x = 0
...     while x < limit:
...             x += 2
...             yield x
...
>>> evens()
<generator object at 0xf6f7454c>
>>> list(evens())
[2, 4, 6, 8, 10]
>>> sum(evens())
30

A generator can be used to create a list.  However, sum will process the
generator directly.  Note that with a list or a tuple ALL of the
elements must be exist at the same time.  sum with a generator can
accumulate the total using one element at a time.

On Tue, 2004-10-19 at 11:03, Bill Mill wrote:
> Hans,
> 
> max() and min() are not class methods because they are useful outside
> the context of lists. For example:
> 
> >>> max(1,2,3,4,5,4)
> 5
> 
> Thus, making max and min methods of the list class (or of all sequence
> classes) doesn't really make sense.
> Now, sum() is a bit more complicated at first blush, but not really.
> We want sum to work with all numerical sequence types - namely, lists
> *and* tuples. Since tuples have no public methods, and we don't want
> to repeat ourselves by including sum() as a method for both lists and
> tuples, we make it a global function.
> 
> Peace
> Bill Mill
> bill.mill at gmail.com
> 
> PS I don't know the exact reason behind sum(), so I took a shot at it.
> That's just how I made sense of it; if you know better please
> contradict me.
> 
> 
> On Tue, 19 Oct 2004 15:29:45 +0100 (BST), Hans Fangohr
> <h.fangohr at soton.ac.uk> wrote:
> > Dear all,
> > 
> > I was looking at what you can do with lists in Python. There are
> > basically two sets of commands: (i) methods doing something with a
> > list (such as sort(), reverse(), count(), ...) and (ii) functions that
> > take a list as an argument (such as sum(), max(), min()).
> > 
> > I would expect that there is a rationale behind this choice -- would
> > anyone know what this is or where I can find more information?
> > 
> > Many thanks,
> > 
> > Hans
> > _______________________________________________
> > Tutor maillist  -  Tutor at python.org
> > http://mail.python.org/mailman/listinfo/tutor
> >
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp



More information about the Tutor mailing list