I was looking at a stackoverflow question (if else in a list comprehension) and decided to try the following line
[ a if a else "Exception" for a in range(10) ]
,
and got the following list
[ "Exception", 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
as an output. I had expected the output to be
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
because zero is itself, just as the other numbers were evaluated. Thinking to test whether the behavior was affecting only the first index, I tried
[ a if a else "Exception" for a in range( 1, 10 ) ]
which outputed
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
and was what I would have not expected if the behavior was specific to the first index. Given the results so far, I tried the following thinking there was something particular about 0
being in the iterable.
[ a if a else "Exception" for a in [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ] ]
and
import numpy
[ a if a else "Exception" for a in numpy.zeros(10) ]
which resulted in the following for both cases
[ "Exception", "Exception", "Exception", "Exception", "Exception", "Exception", "Exception", "Exception", "Exception", "Exception" ]
If someone could explain this behavior to me, I would appreciate it. It appears that 0
being in the iterable could be triggering the unexpected behavior, but I am not confident on that conclusion.