Cleaning up conditionals

Deborah Swanson python at deborahswanson.net
Fri Dec 30 18:00:02 EST 2016


BartC wrote:
> Sent: Friday, December 30, 2016 2:11 PM
> 
> On 30/12/2016 21:20, Deborah Swanson wrote:
> > I've already learned one neat trick to collapse a conditional:
> >
> > 	a = expression1 if condition else expression2
> >
> > Here I have a real mess, in my opinion:
> >
> > 	if len(l1[st]) == 0:
> >           if len(l2[st]) > 0:
> >               l1[st] = l2[st]
> >           elif len(l2[st]) == 0:
> >               if len(l1[st]) > 0:
> >                   l2[st] = l1[st]
> 
> This doesn't make sense. The main block is executed when 
> len(l1[st]) is 
> 0, but you're testing for len(l1[st])>0 in the last if 
> statement (which 
> can't see the assignment to l1[st], so can never be true).
> Try writing it out on paper using A and B instead l1[st] and 
> l2[st] as 
> they look confusing.
> 
> You might also be evaluating len(l2[st]) twice.
> 
> -- 
> Bartc

Oops, indentation was messed up when I copied it into the email. Should
be this:

		if len(l1[st]) == 0:
                if len(l2[st]) > 0:
                    l1[st] = l2[st]
            elif len(l2[st]) == 0:
                if len(l1[st]) > 0:
                    l2[st] = l1[st]



More information about the Python-list mailing list