Cleaning up conditionals

Deborah Swanson python at deborahswanson.net
Sun Jan 1 17:58:40 EST 2017


Steve D'Aprano wrote
> Sent: Saturday, December 31, 2016 10:25 PM
> 
> 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.

This is a very nice explanation of why Chris' statement is valid python
and I completely understand it, though I didn't see how it worked when I
wrote the message you're quoting. Unfortunately this isn't the part that
still gives me trouble.

The real troublemaker here for me, is what should new_value be defined
to be?

It will be either l1[v] or l2[v], depending on which one is non-empty.
But I still don't see any way this terniary assigns the correct value to
the correct field. 

If we back up to your Step One, it's clear that this dilemma is present
from the get-go.

(1) Step One: the naive code.

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

Here the assumption is that new_value is the same for both if and else.
But it isn't. Here's the actual desired outcome:

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

That's why I've been saying that 

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

works beautifully if you are computing a value, but it doesn't work at
all if you're selecting a row to copy the field value from the other row
to.



More information about the Python-list mailing list