Cleaning up conditionals

Peter Otten __peter__ at web.de
Sat Dec 31 11:24:35 EST 2016


Deborah Swanson wrote:

> Here I have a real mess, in my opinion:

[corrected code:]

>         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]

> Anybody know or see an easier (more pythonic) way to do this? I need to
> do it for four fields, and needless to say, that's a really long block
> of ugly code.

By "four fields", do you mean four values of st, or four pairs of l1, l2, or 
more elif-s with l3 and l4 -- or something else entirely?

Usually the most obvious way to avoid repetition is to write a function, and 
to make the best suggestion a bit more context is necessary.





More information about the Python-list mailing list