List Question

Paul McGuire ptmcg at austin.rr.com
Tue Oct 2 18:23:37 EDT 2007


On Oct 2, 4:58 pm, Pablo Ziliani <pa... at decode.com.ar> wrote:
> Paul Hankin wrote:
> > On Oct 2, 10:06 pm, brad <byte8b... at gmail.com> wrote:
>
> >> How is this expressed in Python?
>
> >> If x is in y more than three times:
> >>      print x
>
> >> y is a Python list.
>
> > Simple and readable:
> > if len([a for a in y if x == a]) > 3:
> >     print x
>
> > Or the slightly-too-flashy version:
> > if sum(1 for a in y if x == a) > 3:
> >     print x
>
> <joke>
>
> I always use this full-featured, all-inclusive, rock-solid version (see
> the try/except block):
>
> count = i = 0
> x = 1
> y = [1,2,3,4,5,1,2,3,4,1,2,1]
> try:
>     while count < 3:
>         if y[i] == x:
>             count += 1
>         i += 1
> except RuntimeError:
>     pass
> except IndexError:
>     pass
> else:
>     print x
>
> </joke>
>
> Sorry, couldn't resist...- Hide quoted text -
>
> - Show quoted text -

Well, there is an advantage to your method/madness, in that it does
short-circuiting once the magic count of 3 is found.  If the list
contained *many* entries, or if the predicate were expensive to
evaluate, or if the count were likely to be satisfied within the first
few list elements, your approach beats the other count or sum
suggestions (since they evaluate all list entries).

Here's a version of your code using itertools.takewhile:

count = 0
for a in itertools.takewhile(lambda _:count<3,y):
    count += (x==a)
if count==3:
    print x

-- Paul





More information about the Python-list mailing list