[Tutor] using conditional expression
Manprit Singh
manpritsinghece at gmail.com
Thu Oct 8 15:22:16 EDT 2020
Dear sir ,
Let us consider a problem where i have to make a new list of all even
values present in an existing list . Now if the existing list has no even
item , the newly constructed list will be empty . Now i have to write a
program that prints the new list if it has even value , otherwise it should
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)
Here in this example a conditional expression is used .
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)
Which way should be preferred to solve this kind of problem ?
need your comments
Regards
Manprit Singh
More information about the Tutor
mailing list