Home » Programming » Python » Python For Loop

How to Use ‘for’ Loops in Python, With Examples

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.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment