Twitter LogoFacebook Logo
For Loops or For Statement
Learn how to use the For Statement to create loops.
By: King

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

winning_lottery_numbers = [25, 2, 16, 7, 47, 23]

for number in winning_lottery_numbers:
    print(number)

In the example, we used the For Statement to iterate through all the items in the list.

"number" is a temporary variable that represents the current number in the list at the time of the iteration. It will keep going until it reaches the end of the list.

Output

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.


For example, if we do range(10), it will create a list that is filled with numbers from 0 to 9.

With this, we can combine it with the For Statement to get the current index of the iteration.

for index in range(10):

   print(index)

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.


For example, if we have range(0, 10, 5), it will create a list with 0 and 5. This is because the first 2 parameters - 0 & 10 represents the range of the numbers. The third parameters determines how much to jump.

Since the range starts at 0, the next number would be 0 + 5. Then the next number would be 5 + 5. But since the range only goes from 0 - 9, it will not add the last number.

for index in range(0, 10, 5):
   print(index)

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():

weather = {'NYC': '90', 'Chicago': '100', 'Washinton D.C.': '112'}


for city, degrees in weather.items():
    print("The temperature in " + city + " is " + degrees + " degrees")

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.


Note that the items() function is necessary for this to work.


Sign In