The continue statement in Python
In addition to the break
instruction, which terminates the loop, there is also the continue
instruction, which starts a new iteration of the loop. This instruction can sometimes be useful for simplifying code.
Let us have a list lst
:
lst = [1, 2, 3, 4, 5]
Let's output all elements from it except the number 3
. To do this, under the block with the condition, we write the instruction continue
. At the same time, we specify the function print
in the first block of the cycle:
for el in lst:
if el == 3:
continue
print(el) # 1, 2, 4, 5
Given a set:
tst = {'a', 'b', 'c', 'd', 'e'}
Extract all elements from it except the symbol 'd'
.
Given a list:
tst = [6, 3, -2, 8, -4, 9]
Remove all elements from it except the negative ones.
Given a list:
tst = ['a', 'b', 'c', 'd', 'e']
Get the string 'acde'
from it.