pythonpython-3.xfor-else

How not to execute else statement of for-loop when if statement is satisfied at least once?


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?


Solution

  • The else of a for-loop will only be executed if no break was encountered. Thus, a for-else statement is not appropriate for finding multiple elements in a list since the first break will stop the loop.

    Instead, use a list-comprehension and print accordingly based on the result.

    lst = [100, 2, 1, 3000]
    
    less_than_five = [x for x in lst if x <  5]
    
    if less_than_five:
        print(*less_than_five)
    else:
        print('There are no elements in this list greater than 5.')