# [Tutor] list comprehension with else

Sydney Shall s.shall at virginmedia.com
Sun Jan 18 17:43:42 CET 2015

```On 18/01/2015 13:41, Asokan Pichai wrote:
>
> On Sun, Jan 18, 2015 at 6:50 PM, Sydney Shall <s.shall at virginmedia.com
> <mailto:s.shall at virginmedia.com>> wrote:
>
>     I am a beginner and I have a question of syntax.
>
> Welcome!
>
>
>     I am just learning to use list comprehension, which oc course, I
>
>     However, I am stuck with a specific problem of how to incorporate an
>     else in a list comp-rehension. I cannot do it.
>
>     The following snippet of code does what I need. But, perhaps I am
>     solving this math error problem incorrectly.
>     The problem is I am occasionally getting exactly zeros when I need
>     to obtain the logarithm of the number.
>
>     for i in range(len(cap)):
>
> Using a for loop like this is generally a poor idea.
>
> for aCap in cap:
>
> is the more pythonic way. And also will help you translate to a list
> comprehension easily
>
>              if cap[i] == 0.0:
>                  tmp = math.log(1.0)
>                  lncap.append(tmp)
>
> Possibly lncap.append(math.log(1.0)) or even lncap.append(0) is simpler
>
>              else:
>                  lncap.append(math.log(cap[i]))
>
>
> Having said that above your present code, let me try to explain the
> thought process behind constructing the list comprehension for your
> purpose. It is possible that what you need is not an else in the list
> comprehension
>
> lncap = [ f(aCap) for aCap in cap]
>
> will be the starting point;  where f() will need to provide either
> math.log(aCap) or 0 as we saw earlier.
>
> You can actually write an auxiliary function f that does just that; like say
> def f(p):
>        if p == 0.0:
>            return 0.0
>        return math.log(p)
>
> Or write the list comprehension as:
>
> lncap = [ (math.log(aCap) if aCap > 0 else 0.0) for aCap in cap]
>
> Hope this helps
Thanks. perfect. Thanks especialy for the explanation.

--
Sydney
```