[Tutor] Python program to remove first four even numbers from a list
Dennis Lee Bieber
wlfraed at ix.netcom.com
Sat Oct 16 14:40:59 EDT 2021
On Sat, 16 Oct 2021 22:25:02 +0530, Manprit Singh
<manpritsinghece at gmail.com> declaimed the following:
>In this program i have used multiple if statements inside for loop. My
>
>question is placing multiple if statements inside a for loop is a right
>
>approach as i have adopted in this example?
>
If the code produces the result you expect, then by definition it is
NOT WRONG. It may be inefficient, inelegant (or even downright ugly) -- but
that determination can only be made in relation to what some one has
decreed is "proper"... eg: a corporate code review process, running through
"linters", or a Python equivalent of https://en.wikipedia.org/wiki/MISRA_C
>Secondarily this example can be done with list comprehensions ?
>
So far as I can tell -- NO. List comprehensions process one list
element at a time, and there is no means of having an external "counter"
modified within the comprehension.
I could see one improvement... Using an enumerated sequence in the loop
would allow you to append the remaining sequence contents in one chunk once
you've reached the count limit, and you could then break out of the loop
entirely, rather than repetitively doing all those comparisons even though
the counter says you are done testing.
CAVEAT: newer Pythons keep adding more and more C-isms to the language.
First we got some ternary expression (which I've never used in Python --
the syntax just looks ugly to me, like something from an HP calculator
programmed in RPL -- in an HP48 and up, it is elegant -- but not in
Python), and more recently some sort of assignment expression; it is just
vaguely possible an assignment expression would allow for incrementing your
counter within the comprehension.
--
Wulfraed Dennis Lee Bieber AF6VN
wlfraed at ix.netcom.com http://wlfraed.microdiversity.freeddns.org/
More information about the Tutor
mailing list