[Tutor] If - else Vs OR
Peter Otten
__peter__ at web.de
Tue Jul 21 15:03:33 EDT 2020
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.
More information about the Tutor
mailing list