[Tutor] Handling Generator exceptions in Python 2.5

Joe jopython at gmail.com
Sat Jun 20 18:50:35 CEST 2009


Dave,

Thanks for enlightening me and providing a solution.
I am a recent Python convert (from Perl). Hence the confusion about 
generators.(Coroutines are not a standard part of Perl anyway)

- Joe


Dave Angel wrote:
> Joe Python wrote:
>
>> I have a generator as follows to do list calculations.
>>
>> *result = [(ListA[i] - ListB[i-1])/ListA[i] for i in range(len(ListA))]*
>>
>> The above generator, throws '*ZeroDivisionError*' exception if 
>> ListA[i] =
>> 0.
>> Is there a way to say 'Don't divide by ListA[i] if its equal to 0 
>> (within
>> that statement)'.
>>
>> Sorry if this question sounds too stupid.
>>
>> TIA
>> Joe
> Doesn't sound stupid to me at all.
>
> Short answer is a conditional expression. Replace
> (ListA[i] - ListB[i-1])/ListA[i]
> with
> (ListA[i] - ListB[i-1])/ListA[i] if ListA[i] else 1.0
>
> and you'll see 1.0 whenever ListA[i] == 0, and your original value 
> otherwise.
>
>
> But I see a couple of other things. You're calling this a generator 
> when it's a list comprehension. For short lists, that frequently 
> doesn't matter, but in case it does, you could start by replacing the 
> braces on the outside with parentheses.
>
> Next question is the two lists are the same length. And final one is 
> whether you really meant the offset of one when accessing ListB. If 
> the lists are both of length 4, you're doing something like
> (a0 - b3)/a0 (a1-b0)/a1 (a2-b1)/a2 (a3-b2)/a3
>
> In other words, you're using the last item of ListB for the first 
> division.
>
> If that's really what you want, consider the following generator:
> gen = ((a-b)/a if a!=0.0 else 1.0 for a,b in zip(ListA, 
> ListB[-1:]+ListB))
>
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



More information about the Tutor mailing list