[Tutor] list comprehension with else

Alan Gauld alan.gauld at btinternet.com
Sun Jan 18 16:49:49 CET 2015

On 18/01/15 13:20, Sydney Shall wrote:

> 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)):

Its usually better to iterate over the collection rather than use indexing:

for item in cap:

>          if cap[i] == 0.0:

Its usually a bad idea to compare floats for equality. It's better to 
define a small limit value and check if they are within the range.
like this

e = 0.0000000001  # or whatever

if val-e <= cap[[i] <= val+e:
     do something.

In your case where you test against zero it simplifies to

if -e < cap[i] < e:
     do something

>              tmp = math.log(1.0)

log(1) is a constant (0) so you might as well just say

>              lncap.append(tmp)


>          else:
>              lncap.append(math.log(cap[i]))

But won't this cause you to have really dodgy results? How do you 
distinguish genuine log(1) values from your pseudo log(0) values?
Or does it not matter?

> I have set mu options to plain text.

Thanks, always appreciated.

While you can make comprehensions do what you want its not always a good 
idea. Sometimes its better to revert to explicit loops if the complexity 
of the comprehension gets too great.

But in your case its fairly simple to use a conditional expression:

lncap = [ 0.0 if (-e < item < e) else math.log(item) for item in cap]

Alan G
Author of the Learn to Program web site
Follow my photo-blog on Flickr at:

More information about the Tutor mailing list