for loops

Resources

  • for statement in the official documentation.
  • for loops in Real Python.

for

for allows us to execute a block of code for each item. The variable defined after the for keyword will take the value of each item, one at a time, one for each iteration.

What would happen if we executed the following code? How would you fix it?

Tip

Internally the for loop works by calling the next on an iterator from the given iterable. An iterator is an object that, when given to the next function, supports the generation of one item at a time, until it runs out of items. So the previous for loop would be, more or less, equivalent running the following code.

Python has another way of doing loops, the while statement.

break

At any iteration the loop could be completely stopped, broken, by using the break statement.

continue

The continue statement allows us to move to the next iteration without running the rest of the code in the block.

range

This kind of for loop, the one implemented in Python, in other languages is known as a foreach loop. To have the functionallity available in other programming languages, in which the for statement just iterates over some numbers, you could combine a for loop with the range function.

Write a for loop that prints the first 10 natural numbers.

Note

You can use a list or the range function.

Note

With a list.

With the range function.

Create a program that writes the following:

Note

There are many ways of solving this exercise, here you have some.

Using map and range.

Using a list comprenhension.

enumerate

It is quite common to require both the item and its index. We could do it like:

However, this pattern is so common that Python have solved it using the function enumerate.

Enumerate works by creating an iterator of tuples with two elements: the index, and the original item.

And since Python supports mutiple assigment what we are doing in the for loop is equivalente to: