In Python, we can use the For Statement to iterate through all the items of a collection or to repeat a set of code for a certain amount of time.
In Python, we can use the For Statement to iterate through all the items of a collection or to repeat a set of code for a certain amount of time.
Syntax
for <variable> in <collection>:
for <variable> in <range>:
Example 1: Collection
25, 2, 16, 7, 47, 23
Example 2: Range
Sometimes you may want to create a loop that will run a certain amount of times while keeping track of the current index of the iteration. We can do this with the range() function.
The range() function will create a list of numbers sequentially put together.
With this, we can combine it with the For Statement to get the current index of the iteration.
for index in range(10):
This will print out: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
The range() function also let us specify the amount it would jump to the next number. By default it is set to one.
Output: 0, 5
Example 3: Dictionary
An interesting thing we can also do with the For Statement is to unpack a dictionary and get the key and value at the same time.
Syntax
for <key>, <value> in <dictionary>.items():
In the example, there is a dictionary call weather with temperature data from different cities. We used the For Statement to get the city and degrees at the same time.