[Tutor] If - else Vs OR

dn PyTutor at DancesWithMice.info
Tue Jul 21 16:26:45 EDT 2020


On 7/22/20 7:03 AM, Peter Otten wrote:
> Manprit Singh wrote:
> 
>> Dear all,
>> Consider a problem in which there is a list a, which can contain even as
>> well as odd numbers.  For Example  a = [2, 3, 4, 6, 8]
>> Now  i have to  filter out all even numbers from this list, and make a new
>> list a1 that contains all odd numbers . In case,  if the list a does not
>> contains any odd number, then the  resultant will be an empty list , this
>> resultant list can be made by :
>> a1 = [ i for i in a if i%2 !=  0]
>> So, a1 will be empty if list a does not contain any odd number , and if
>> list a has one or more odd numbers then a1 will contain all those odd
>> numbers .
>> i have to write a program which will print "Empty List" if a1 is empty and
>> print list a1 if a1 is not empty :
>> 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")
> 
> I think they are both fine, as is
> 
> (3)
> 
> print(a1 if a1 else "Empty list")
> 
> Another idea: you might try and simplify the if part of the list
> comprehension.


Agreed, I was amused at the taking-advantage of 'truthiness' in the 
print() but not in the list-comprehension!

Further, some suggest that a well-chosen name, for the string-constant 
in this case, will not only assist in reading-comprehension but also 
ease maintenance (eg should the users decide to use a less technical 
explanation than "Empty list" -> "No data available").

Of the original options, doesn't the explicit if...print() seem more 
readable? Is @Peter's contribution more readable than either/both?

If the reader is likely to be more 'Python apprentice' than 'master', 
then recommend avoiding either/both 'short-cuts'.

OTOH, if decide for concise-and-powerful, then may as well go for 
both/broke!
-- 
Regards =dn


More information about the Tutor mailing list