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

Active January 04, 2022    /    Viewed 186    /    Comments 0    /    Edit


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

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!



Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount