[Tutor] Appropriate use of assignment expression

Richard Damon Richard at Damon-Family.org
Sat Nov 20 09:33:53 EST 2021


On 11/20/21 9:03 AM, Alan Gauld via Tutor wrote:
> On 20/11/2021 11:52, Manprit Singh wrote:
>> Dear sir,
>>
>> Consider a problem of list of numbers as given below :
>>
>> ls = [234, 5445, 613, 959, 3441, 212, 239]
>>
>> Now i only need those numbers from the list ls which are palindrome, into a
>> new list, doing this way gives the result :
>>
>> ans = [ele for ele in ls if (y:=str(ele))==y[::-1]]
>> print(ans)    # Gives result given below which is the right answer
>> [5445, 959, 212]
>>
>> Is it ok to use assignment expressions in this way ?
> If it works it must be OK.
>
> There has been a lot of debate just recently on the main
> Python list about how and when you should use the new
> "walrus" operator. But it is so new there has not been
> time for a community consensus to form over the best
> practice. So for now, if it works, you can use it.
>
> Personally, I've been burned so many times with assignments
> inside tests in C that I try my best to avoid it if at all
> possible. (I have found occasional cases where it just
> makes things so much simpler that it's foolish not to - this
> example may even be such a case!
>
One BIG thing to point out is that C leaves a lot of details about the 
order things happen to up to the implementation, so this sort of 
statement might not work there.

Python defines the order much more strictly, so we KNOW that y will be 
set to str(ele) before we reverse it with y[::-1] so we have the needed 
promises to be able to say that it will 'work'.

In this case, the question seems to not really be 'Does it work' but is 
it 'good' in the sense of being readable, and that question doesn't 
always have a clean answer, as like many things, it depends.

Personally, I tend to like to decompose into clearly defined functions 
so I might create as is_palindrome function which takes a string and 
returns a bool that it true for a palindrome input string. That gives a 
LONGER program, and maybe a bit slower (due to the added call) but one 
easier to mentally parse, and thus one I would feel more confident that 
it will work.

-- 
Richard Damon



More information about the Tutor mailing list