Examples of how to skip an iteration in a loop if a condition is verified in python:
Table of contents
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')continueelse:print(i)
gives
abiteration skippeddef
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
163a845b296c
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:continueelse:print(j)print(i[0])print()
gives
163a84b296c
Another example of how to skip the iteration for both loops if the value 5 is found:
for i in list_of_tuples:sc = Falseif 5 in i[1]:sc = Truecontinueelse:for j in i[1]: print(j)if sc: continueprint(i[0])print()
gives
163a296c
