Cleaning up conditionals

BartC bc at freeuk.com
Fri Dec 30 17:11:16 EST 2016


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


More information about the Python-list mailing list