[Tutor] Counting matching elements in sequences

Kalle Svensson kalle at lysator.liu.se
Wed Dec 10 14:13:59 EST 2003


[Magnus Lycka]
> > >def alleq(seq):
> > >    for item in seq[1:]:
> > >        if item != seq[0]:
> > >            return False
> > >    return True
> 
> Gregor wrote: 
> >  >>> def alleq(seq):
> >  ...     return seq == seq[:1]*len(seq)
[...]
> With very big sequences, there might be
> a memory issue as well, since "seq[:1]*len(seq)"
> makes an extra list[.]

But so does "for item in seq[1:]:".  I think that the cost of the
extra comparison caused by removing the slice would often be smaller
than the cost of copying the list.  Haven't done any profiling,
though.

Peace,
  Kalle
-- 
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.



More information about the Tutor mailing list