I am trying to check all elements in a list to see if they meet the condition "less than 5". What I'm trying to do is if no numbers in my list are less than 5, I want to print a statement "There are no elements in this list less than 5.", otherwise print only those numbers that are, and not "There are no elements in this list less than 5." also.
list = [100, 2, 1, 3000]
for x in list:
if int(x) < 5:
print(x)
else:
print("There are no elements in this list less than 5.")
This produces the output:
2
1
There are no elements in this list less than 5.
How can I get rid of the last line of that output?
The
elseof afor-loopwill only be executed if nobreakwas encountered. Thus, afor-elsestatement is not appropriate for finding multiple elements in a list since the firstbreakwill stop the loop.Instead, use a list-comprehension and print accordingly based on the result.