List Question

Pablo Ziliani pablo at decode.com.ar
Tue Oct 2 23:58:07 CEST 2007


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...



More information about the Python-list mailing list