Cleaning up conditionals

Steve D'Aprano steve+python at pearwood.info
Sun Jan 1 01:24:58 EST 2017


On Sun, 1 Jan 2017 02:58 pm, Deborah Swanson wrote:

>> It's possible to select either l1 or l2 using an expression,
>> and then subscript that with [v]. However, this does not
>> usually make for readable code, so I don't recommend it.
>> 
>> (l1 if whatever else l2)[v] = new_value
>> 
>> ChrisA
> 
> I'm not sure I understand what you did here, at least not well enough to
> try it.


The evolution of a Python programmer :-)


(1) Step One: the naive code.

if condition:
    l1[v] = new_value
else:
    l2[v] = new_value


(2) Step Two: add a temporary variable to avoid repeating the assignment

if condition:
    temp = l1
else:
    temp = l2
temp[v] = new_value


(3) Step Three: change the if...else statement to an expression

temp = l1 if condition else l2
temp[v] = new_value


(4) Step Four: no need for the temporary variable

(l1 if condition else l2)[v] = new_value





-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.



More information about the Python-list mailing list