Skip to main content

Python: 13 Iteration - Loops - For

A for loop is used to iterate over a known number of items or a list.

It is used when you know how many times the loop will need to run.

The loop below will print out all of the items in a list.

The indented code will run for each item in the list.

characters = ["Mario", "Sonic", "Crash"]
for x in characters:
print(x)

If you want to run a loop a set number of times we use the range() function

There are two different range functions. One takes one argument.

This number is exclusive this means that we don't include this number and we start at 0.

range(6) will start at 0 and finish at 5.

for x in range(6):
print(x)

There is also a two argument version which includes the first value and excludes the second value.

range(4, 10) will start at 4 and finish at 9

for x in range(4, 10):
print(x)

For more information about Python for loops look on W3 Schools.