Earlier, we looked at while
loops. This construction repeats a set of actions. Anything beyond repetition requires additional means of storing the state.
Here, we will take the counter that we change in the loop as an example. When working with collections, we choose which item we're working on within the current iteration. So should we use a variable counter every time?
All programmers want to automate routine work, and language writers are no exception. That's why Python has a different kind of loop for working with collections — the for
loop.
It's worth noting that this loop isn't like loops with the same name in other programming languages. This loop is just a supplement to the variable-counter loop termination condition in many languages.
Python has gone further, so in this language, the for
loop immediately goes through the elements of the input collection, and you often don't need to think about the index at all.
The syntax
The for
loop is simple:
for element in collection:
print(element) # This is the body of the cycle
Note that loops don't have an explicit termination condition in the simplest case. The loop stops when the collection runs out of items.
The example above will work for tuples and lists. In this case, we will see all elements. And you can also iterate — traverse a collection. In this case, the loop variable element
will contain all characters of the string in turn:
for c in 'Hello!':
print(c)
# => H
# => e
# => l
# => l
# => o
# => !
But what do we do when we need to get the list of items one by one and change those items? After all, we need the index of each element.
Python has the handy enumerate
function for this. This function provides each element with an index and puts them into a tuple together. These tuples are usually unpacked right in the first string of the loop:
items = ['foo', 'bar', 'baz']
for (index, elem) in enumerate(items):
items[index] = elem + '!'
print(items) # => ['foo!', 'bar!', 'baz!']
In this loop, we replaced each element with the original value, with the string '!'
added at the end. We can write this code in a slightly different way:
items = ['foo', 'bar', 'baz']
for (index, _) in enumerate(items):
items[index] += '!'
print(items) # => ['foo!', 'bar!', 'baz!']