The for loop

The for loop is the classical form of the loop—it literally goes over an iterable (collection of values) and performs the same computation for each value, consecutively. The code within the loop may or may not be using the value for which it is computed.

For example, if we just need to run some specific code N times, we can run the loop over the range object that contains N values. Consider the following example:

>>> for i in range(3):
>>> print(i)
0
1
2

Here, we execute a built-in range function (which we discussed in Chapter 3, Functions) and run a loop, printing each element in this loop.

Any other iterable would suffice as well, including strings, sets, lists, tuples, dictionaries, and generators. All the code in the scope of the loop will be repeated as many times as there are elements in the iterable. In the following code, we loop through the characters in a string, printing each of them:

>>> for char in 'Jack':
>>> print(char)
J
a
c
k

Loops require indentation—just like functions. In contrast to functions, however, variables assigned in the loop (the last value they were assigned to), will be accessible from the outside of this indentation. The looping variable ( el in the first example, and char in the second) can be named as you see fit.

In fact, we can pass more than one value using unpacking. Here is one example. We're iterating over a dictionary, using its items method. In the first line of the loop, we can define two variables, the first representing the key, and the second the value. Once defined, both variables can be used in the code—in this case, printed. If we were to state one argument instead, it would be assigned a tuple of key-value pairs:

>>> person = {
'name':'Jim',
'surname':'Hockins'
}

>>> for k, v in person.items():
print(k, ':', v)

name : Jim
surname : Hockins

As a result, key and value are printed for each pair in the dictionary—name : Jim.

Any number of loops can be nested one within the other—as many as you like. In that case, an internal loop will require an additional level of indentation. Note, however, that loops are generally time-consuming, and nesting increases time exponentially. Typically, pay attention if you need to nest two or more loops; there may be a better way.

The power of loops can be expanded, leveraging built-in additional tools. Let's take a look.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.248.211