Syntax and features of the for Python loop

by Alex
Syntax and features of the for Python loop

The python cycles – for and while are programming language statements, that is, iteration statements that allow code to be repeated a certain number of times.

For loop syntax

As mentioned earlier, the for loop in Python is a loop-based iterator. It traverses list and tuple elements, strings, dictionary keys, and other iterated objects. In Python, the loop starts with the for keyword, followed by an arbitrary variable name that will store the values of the next object in the sequence. The general syntax for...in in python is as follows:

for in :
else:

The elements of the “sequence” are looped through one by one by the “variable” of the loop; to be precise, the variable points to the elements. For each element an “action” is performed. An example of a simple for loop in Python:


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

The else block is special; while the Perl programmer is familiar with it, it is an unknown construct to programmers who work in C and C++. Semantically, it works in exactly the same way as the while loop. It will only be executed if the loop has not been “stopped” by the break operator. Thus, it will only be executed after all the elements of the sequence have been passed.

The python interrupt operator is break

If a for loop in a program should be interrupted by a break statement, the loop will be terminated and the program flow will continue without performing any actions from else. Usually break phrases in pyton are associated 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("Good thing there were no dumplings!")
print("Dinner is over.")

If we run this code, we will get the following result:

Great, tasty chops
I don't eat dumplings!
Dinner's over.

We remove “dumplings” from our food list and get the following:

Great, tasty chops
Great, tasty eggs
Great, tasty nuts
Good thing there were no dumplings!
Dinner's over.

The python skip operator – continue

Suppose we just need to skip “dumplings” and continue eating. Then we need to use the continue operator, to move on to the next item. In the following little python script, we use continue to continue, iterating through the list when we encounter dumplings.

edibles = ["chops," "dumplings," "eggs," "nuts"]
for food in edibles:
if food == "dumplings":
print("I don't eat dumplings!")
continue
print("Fine, delicious " + food)
else:
print("I hate dumplings!")
print("Dinner is over.")

The result will be as follows:

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

Iterating through lists with range()

If you need to access the list indexes, it is not obvious how to use the for loop for this task. We can access all the elements, but the element index remains unavailable. There is a way to access both the item index and the item itself. To do this, use the range() function in combination 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])

You will get the following output:

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

Note. If you apply len() to a list or tuple, you will get the corresponding number of elements in that sequence.

The pitfalls of iterating over lists

If you’re iterating over a list, it’s best to avoid changing the list in the body of the loop. To see what can happen, look at the following example:


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

What will print(colours) print?

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

To avoid this, it is best to work with the copy using slices, as done in the following example:


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

You will end up with the following:

['red', 'black']

We have changed the list of colours, but this change has no effect on the loop. The elements that have to be iterated remain unchanged during the loop.

Enumerate in python 3

Enumerate is a built-in Python function. Most beginners and even some advanced programmers don’t know about it. It allows us to automatically count loop iterations. Here’s an example:


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

The enumerate function also takes an optional argument (the start value, the default is 0), which makes it even more useful.


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

Related Posts

LEAVE A COMMENT