[Tutor] If - else Vs OR
Alan Gauld
alan.gauld at yahoo.co.uk
Tue Jul 21 19:49:19 EDT 2020
On 21/07/2020 17:37, Manprit Singh wrote:
> i am writing 2 solutions to this problem . My question is which one method
> should be preferred
> sol 1) :
>
> a = [2, 3, 4, 6, 8]
> a1 = [i for i in a if i%2 != 0]
> if a1:
> print(a1)
> else:
> print("Empty list")
>
> sol 2) :
>
> a = [2, 3, 4, 6, 8]
> a1 = [i for i in a if i%2 != 0]
> print(a1 or "Empty list")
For ease of maintenance you should always aim to maximize the clarity
of your intent. In the first case its easy to see that its an if/else
situation. In the second case you are relying on short circuit
evaluation of a boolean expression. Somebody has to decode it.
Reading it as written it sounds like you don't care which value
gets printed, (ie print either of them it doesn't matter) but
in fact you you do, you just rely on the short circuit evaluation
of booleans to choose.
So my vote is option 1 every time. It's much clearer what the
code is trying to do.
If for some reason (and it would be a very unusual reason) you need
to do it in a single line you could use the conditional expression:
print(a1 if a1 else "Empty list")
That retains the expression of intent even though it is still more
cumbersome for the reader to parse. But its definitely better than
the "clever code" boolean 'or' based solution.
--
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