syntax difference

Chris Angelico rosuav at gmail.com
Tue Jun 19 07:03:55 EDT 2018


On Tue, Jun 19, 2018 at 8:52 PM, Bart <bc at freeuk.com> wrote:
> On 19/06/2018 11:33, Steven D'Aprano wrote:
>>
>> On Tue, 19 Jun 2018 10:19:15 +0100, Bart wrote:
>>
>>> * Swap(x,y) (evaluate each once unlike a,y=y,x)
>>
>>
>> Sigh. Really? You think x,y = y,x evaluates x and y twice?
>
>
> Yes. Try:
>
> count=0
>
> def fn():
>         global count
>         count=count+1
>         return 1
>
> a=[10,20,30,40]
> b=[1,2,3,4]
>
> a[1],b[fn()] = b[fn()],a[1]
>
> print (a)
> print (b)
> print ("Count",count)
>
> b[fn()] is evaluated twice.

Ahh right. You never mentioned that your swap targets had complex
expressions in them. What a horrible pity that Python requires you to
be explicit that fn should be called only once:

idx = fn()
a[1], b[idx] = b[idx], a[1]

It's the price you pay for orthogonality, I guess.

ChrisA



More information about the Python-list mailing list