[Tutor] Appropriate use of assignment expression
Alan Gauld
alan.gauld at yahoo.co.uk
Sat Nov 20 09:03:18 EST 2021
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!
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list