This article will show you how to use for loops in Python 3 and provide examples.
Loops are one of the fundamentals of programming. So you’ll use them almost constantly.
Data in computer software is often stored in arrays (or lists), for example, a record of students enrolled in a course, with each item in a list representing a student.
These arrays of data need to be processed – and this is done using loops that step through each item in the array and perform some tasks on each of them.
In the Python programming languages, these arrays are called iterables – a type of data that can be iterated over item by item. It includes variables called lists, tuples, sets, and dictionaries – all of which are arrays of data that can be used in different ways.
Looping Through Iterables with a for Loop in Python
for loops have super simple syntax, so let’s get straight to the code:
# Define a list of students students = ["Sean", "George", "Roger", "Tim"] # Loop through each student in the list of students for student in students: # Print the student print(student)
Watch your indentation! Python uses white space to define what code belongs to what block, so make sure the code you want to run for each item in the for loop is indented underneath it.
As you can see above, the syntax for a for loop is as simple as:
for item in iterable # Code to execute
… so long as a valid iterable (lists, tuples, sets, dictionaries, and even strings) is supplied to the for statement, the items in it will be processed. You can give variable used to access each item whatever variable name you like.
Stopping the Loop with break
If you want to stop iterating through the items if a certain condition is met, use the break statement:
# Define a list of students students = ["Sean", "George", "Roger", "Tim"] # Loop through each student in the list of students for student in students: # Print the student print(student) # Stop executing after reaching George if(student == "George") break
Note that the break statement above comes after the print statement – so ‘George’ would still be printed – execution would stop after this point.
The break statement could occur anywhere inside the for code block, so it could be moved before the print statement if you wished to stop before printing when the condition is met.