[Tutor] using conditional expression

Alan Gauld alan.gauld at yahoo.co.uk
Thu Oct 8 20:17:15 EDT 2020


On 08/10/2020 20:22, Manprit Singh wrote:

> print "Generated list is empty". The most popular way of doing this is :
> 
> list1 = [3, 7, 5, 9, 1]
> list2 = [i for i in list1 if i % 2 == 0]
> if list2:
>     print(list2)
> else:
>     print("Generated list is empty")
> 
> Just need to check if this can be written as given below or not :
> 
> list1 = [3, 7, 5, 9, 1]
> list2 = [i for i in list1 if i % 2 == 0]
> res = list2 if list2 else "Generated list is empty"
> print(res)

Yes it can, it works.

Although arguably it would be more readable to miss out the
redundant variable res and just put the expression in the print:

print(list2 if list2 else "Generated list is empty")

Which ou choose depends on which is most readable sand therefore
maintainable. Conditional expressions can seem confusing to
some readers, and can get very complex if there are more
than 2 options. In that case I'd definitely revert to explicit
if/else.

> Third alternative way is :
> list1 = [3, 7, 5, 9, 1]
> list2 = [i for i in list1 if i % 2 == 0]
> res = list2 or "Generated list is empty"
> print(res)

This was common practice before conditional expressions were
introduced and is still used by some die-hards but is now
deprecated in favour of conditionals.
Conditionals are harder to get wrong and do not abuse a
side-effect of boolean logic implementation (albeit a
guaranteed side effect)!

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