[Tutor] Appropriate use of assignment expression

Dennis Lee Bieber wlfraed at ix.netcom.com
Sat Nov 20 13:07:26 EST 2021


On Sat, 20 Nov 2021 17:22:08 +0530, Manprit Singh
<manpritsinghece at gmail.com> declaimed the following:

>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 ?
>

	And once again, you are really asking about STYLE -- if the code
produces the result you want, it is not wrong. But would a corporate
environment accept this? They may have style guides.

	I'd consider

			... str(ele) == str(ele)[::-1]

to be more legible in most constructs. But since even the [::-1] may be
confusing to those not familiar with some features of slicing, I'm really
more likely to use

			... str(ele) == "".join(reversed(str(ele)))

as it is more explicit about what is being compared. 

	An "assignment expression" would make more sense IF the name that
receives the result is used in later statements. Compare

	if not (errcode := somefunction(...)):
		#no error, continue processing
	else:
		#assumes non-zero is an error
		if errcode = 1:
			#do something
		elsif errcode = 2:
			#do something else
		else:
			#do something for all other error codes

vs

	errcode = somefunction(...)
	if not errcode:
		#no error, continue processing
	else:
		#assumes non-zero is an error
		if errcode = 1:
			#do something
		elsif errcode = 2:
			#do something else
		else:
			#do something for all other error codes


-- 
	Wulfraed                 Dennis Lee Bieber         AF6VN
	wlfraed at ix.netcom.com    http://wlfraed.microdiversity.freeddns.org/



More information about the Tutor mailing list