for loop in python. Syntax, list iteration, break, continue and other features

Цikl for python i cycle while – statements software language, namely: iteration operators, leting repeat code given number time.

Цикл For — сintaxis

As already explained, cinclude for in Python is an iterator based onй per cycleidentity. is he acts by tuple elements и list, vocabulary keys and other iterable objects.

A loop in Python begins with the for keyword, followed by an arbitrary variable name that stores the value of the next object in the given sequence. The general syntax for for…in in python looks like this:

for  in :        else:      

Components “sequences” are listed one after another cycle variable. Or rather, variable points to such elements. For everybody of them “action” is performed.

A simple for loop in Python with a specific example:

>>> languages = ["C", "C++", "Perl", "Python"]  >>> for x in languages:  ...     print(x)  ...  C  C++  Perl  Python  >>>

The else block is specialth. If a programmerыworking с Perl familiarы with him, that for those who interact с C and C++ — this is an innovation. Semantically it functions тidentically while loop.

Only executed when the loop is not “stopped” by the break statement. That is, it is executed only after all elements have passed through the specified sequence.

Break operator in python – break

If the program has a for loop necessary interruptthe break statement, he completeit goesand program flow will contto be without activation from else.

More often break phrases in pythonuyutsya with conditional statements.

edibles = ["chops", "dumplings","eggs","nuts"] for food in edibles: if food == "dumplings": print("I don't eat dumplings!") break print("Great, delicious " + food) else: print("It's good that there were no dumplings!") print("Dinner is over.")

If you run this code, you get the following result:

Great, delicious chops. I don't eat dumplings! Dinner is over.

We remove “dumplings” from the existing list of data and get:

Excellent, delicious chops Excellent, delicious eggs Excellent, delicious nuts Good thing there were no dumplings! Dinner is over.

python skip operator – continue

Let’s say that the user’s antipathy to such products is not so great as to completely abandon their consumption. As a result, the loop continues with the operator continue. The following script uses the statement continue, to continue iterating through the list on “dumpling contact”.

edibles = ["chops", "dumplings","eggs","nuts"] for food in edibles: if food == "dumplings": print("I don't eat dumplings!") continue print("Great, delicious " + food) # this could be code for enjoying food :-) else: print("I hate dumplings!") print("Dinner is over.")

The bottom line:

Great, delicious chops. I don't eat dumplings! Great, delicious eggs Great, delicious nuts I hate dumplings! Dinner is over.

Iterating over lists with the range() function

If you want to access the indexes of a list, it’s not clear how to use a for loop for this purpose. It is possible to access all elements, but the element’s index will remain inaccessible. However, there is a method for accessing both the element’s index and the element itself. For this purpose, the function is used range() combined with the length function len():

fibonacci = [0,1,1,2,3,5,8,13,21]  for i in range(len(fibonacci)):      print(i,fibonacci[i])

Get:

0 0 1 1 2 1 3 2 4 3 5 5 6 8 7 13 8 21

Attention! When applied len() к list or tuple, the corresponding number of elements of the given sequence is obtained.

Difficulties of iterating over lists

When iterating over a list, it is recommended to avoid list dynamics in the loop body. For clarity, we can offer the following option:

colors = ["red"] for i in colors: if i == "red": colors += ["black"] if i == "black": colors += ["white"] print(colours)

What happens when applying print(colours)?

['red', 'black', 'white']

To avoid this, it is recommended to interact with the copy using slices, as in the example below:

colors = ["red"] for i in colors[:]: if i == "red": colors += ["black"] if i == "black": colors += ["white"] print(colours )

Result:

['Red Black']

The list has been changed colours, but this action did not affect the loop. The data that needed to be iterated remained unchanged during the execution of the loop.

Enumerate in python 3

Enumerate is a built-in Python function. Most beginners, as well as some experienced programmers, are not aware of its existence. It allows you to automatically count iterations of the loop. For example:

for counter, value in enumerate(some_list):     print(counter, value)

Function enumerate also takes an optional argument (the value of the origin, taken by default for 0). Which makes it even more efficient.

my_list = ['apple', 'banana', 'cherry', 'peach'] for c, value in enumerate(my_list, 1): print(c, value) # Result: # 1 apple # 2 banana # 3 cherry # 4 peach

Leave a Reply