Оператор for

Оновлено: 24.04.2023

Оператор for використовується для повторення елементів послідовності (таких як рядок, кортеж або список) або іншого ітерованого об’єкта:

for_stmt ::=  "for" target_list "in" starred_list ":" suite
              ["else" ":" suite]

The starred_list expression is evaluated once; it should yield an iterable object. An iterator is created for that iterable. The first item provided by the iterator is then assigned to the target list using the standard rules for assignments (see Заяви про призначення), and the suite is executed. This repeats for each item provided by the iterator. When the iterator is exhausted, the suite in the else clause, if present, is executed, and the loop terminates.

Інструкція break, виконана в першому наборі, завершує цикл без виконання набору речень else. Інструкція continue, виконана в першому наборі, пропускає решту набору і продовжує з наступним елементом або з пропозицією else, якщо наступного елемента немає.

Цикл for виконує призначення змінним у цільовому списку. Це перезаписує всі попередні призначення цим змінним, включаючи ті, що зроблені в наборі циклу for:

for i in range(10):
    print(i)
    i = 5             # this will not affect the for-loop
                      # because i will be overwritten with the next
                      # index in the range

Names in the target list are not deleted when the loop is finished, but if the sequence is empty, they will not have been assigned to at all by the loop. Hint: the built-in type range() represents immutable arithmetic sequences of integers. For instance, iterating range(3) successively yields 0, 1, and then 2.