Python For Loops

The for loop is where you iterate over a sequence (such as a list, tuple, dictionary, or string) or other object until you reach the last item in the object.

The for loop allows you to do things like, perform an operation against each item in a list. For example, you could print out each item, test each item against another value, add up each item in the list, etc.

The for loop is similar to the while loop in the sense that you can make your program run a set of instructions repeatedly. The difference is that, the for loop iterates over a sequence, rather than against a predefined condition.

Here's an example:

Result
Earth
Mars
Neptune
Venus
Mercury
Saturn
Jupiter
Uranus

Here's what the program is doing:

  1. Create a list of planets called planet.
  2. Enter a for loop that iterates through each item in the planet list. The i represents each individual item in the list. This could be called anything. For example, we could've called it planet to better describe the items we're iterating against.
  3. For each iteration, print the current item to the screen.

Breaking a Loop

You can use the break statement to break out of a loop early.

Result
Earth
Mars
Neptune
Venus

A Loop with else

Python lets you add an else part to your loops. This is similar to using else with an if statement. It lets you specify what to do when the loop has finished.

Result
Earth
Mars
Neptune
Venus
Mercury
Saturn
Jupiter
Uranus
That's all folks!

Note that the else doesn't execute if you break your loop:

Result
Earth
Mars
Neptune
Venus

Looping over a Dictionary

If you need to loop over a dictionary, you can access the values in the following manner:

Result
Earth 40075
Saturn 378675
Jupiter 439264

All we're doing here is printing each key and its corresponding value. To get the value, we append square brackets to the dictionary name and insert the key. The planet refers to the key, and the planets[planet] is its value.

You can do a lot more with loops than just print out the values. However, the important thing is, these examples demonstrate how to access the each item as the loop iterates. Once you can do that, you can do all sorts of useful things.