Is there any converse behavior for "else" in a for-else loop?

I have a loop forthat checks a condition. I would like to execute some code if the condition was not met. The following code does the opposite:

a = [1, 2, 3]
for k in a:
    if k == 2:
        break
else:
    print("no match")

"No match" is printed if breaknot reached (for example, for a type condition k == 10). Is there a construct that will do the opposite, that is, run some code, if achieved break?

I know I can do something like

a = [1, 2, 3]
match = False
for k in a:
    if k == 2:
        match = True
if match:
    print("match")

but was looking for a more compact solution without a flag variable.

. , , "" for. , for ( , )

+4
3

, any, .

if not any(k == 2 for k in a):
    print 'no match'

, , :

def f(x):
    return x == 2

if not any(f(k) for k in a):
    print 'no match'
+2

. break.

a = [1, 2, 3]
for k in a:
    if k == 2:
        print("found")    # HERE
        break
else:
    print("no match")
+1

:

a = [1, 2, 3]
for k in a:
    if k == 2:
        print("match")
        break
+1

All Articles