Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - List comphrehension with test to avoid division by zero

Tags:

python

list

numpy

a and b are 1 dimensional numpy arrays (or python lists):

I am doing this:

>>> c = [x/y for x,y in zip(a,b)]

Occasionally b has a zero in it - so a division by zero error occurs.

How can I conditionally check for a 0 value in b and set the corresponding element of c to 0?

like image 740
atomh33ls Avatar asked Feb 12 '26 12:02

atomh33ls


2 Answers

You can use if-else condition inside list comprehension:

>>> c = [x/y if y else 0 for x,y in zip(a,b)]
like image 122
Rohit Jain Avatar answered Feb 15 '26 04:02

Rohit Jain


You can use a ternary expression inside the list comprehension:

[x/y if y!= 0 else 0 for x,y in zip(a,b)]
like image 20
Ashwini Chaudhary Avatar answered Feb 15 '26 04:02

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!