[Tutor] Handling Generator exceptions in Python 2.5
Alan Gauld
alan.gauld at btinternet.com
Fri Jun 19 18:20:45 CEST 2009
"Joe Python" <jopython at gmail.com> wrote
> *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)'.
You could use an 'or' sideffect
result = [(ListA[i] - ListB[i-1])/(ListA[i] or 1) for i in
range(len(ListA))]
But whether dividing by 1 as a default makes any sense will be a
choice depending on the application and data.
Alan G
More information about the Tutor
mailing list