[Tutor] If - else Vs OR
Manprit Singh
manpritsinghece at gmail.com
Tue Jul 21 12:37:51 EDT 2020
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")
More information about the Tutor
mailing list