How to skip an iteration in a loop if a condition is verified in python ?

Published: January 04, 2022

Updated: December 09, 2022

Tags: Python; Loop;

DMCA.com Protection Status

Examples of how to skip an iteration in a loop if a condition is verified in python:

Example with a simple list

In some cases in can be usefull to skip am iteration in a loop if a condition is verfied. To do that a solution is to use "continue"
(see More Control Flow Tools)

list_of_letters = ['a','b','c','d','e','f']

for i in list_of_letters:
        if i == 'c':
                print('iteration skipped')
                continue
        else:
                print(i)

gives

a
b
iteration skipped
d
e
f

Example with nested lists

Let's consider the following list of tuples:

list_of_tuples = [('a',[1,6,3]), ('b',[8,4,5]), ('c',[2,9,6])]

for i in list_of_tuples:
    for j in i[1]:
        print(j)
    print(i[0])
    print()

gives then

1
6
3
a

8
4
5
b

2
9
6
c

Let's skip the second loop if the value 5 is found:

for i in list_of_tuples:
    for j in i[1]:
        if j == 5:
            continue
        else:
            print(j)
    print(i[0])
    print()

gives

1
6
3
a

8
4
b

2
9
6
c

Another example of how to skip the iteration for both loops if the value 5 is found:

for i in list_of_tuples:
    sc = False
    if 5 in i[1]:
        sc = True
        continue
    else:
        for j in i[1]: print(j)
    if sc: continue
    print(i[0])
    print()

gives

1
6
3
a

2
9
6
c