A Professional’s Tutorial to Python For Loops

More control flow, Python terms and concepts

Adam Ross Nelson
7 min readSep 17

For an overview of these tutorials, click here (or click the image).

Welcome to fifth, in a series of tutorials that teach beginner Python specifically for aspiring data scientists. For an overview of these tutorials, click here.

Introduction

A previous tutorial (about if statements and while loops) in this series explored the essence of decision-making with the if statement and ventured into the realm of repetition (or iteration) with the while loop statement. We compared how if and while loops let your code mimic human-like decision making processes on a shopping trip.

These constructs, you might also consider akin to the dials and switches on a machine, empower programmers to carve out dynamic pathways in their algorithms. However, as we push the boundaries of complexity especially for data science, another tutorial remains ahead: the for loop.

A black computer screen with multi-colored computer code.
Image Credit: Author’s illustration created in Canva.com.

Abstract

Python, a prominent language in data science, offers an elegant and flexible construct for iteration: the for loop. This tutorial carefully explains its intricacies, the basic structure, and how it works with iterables such as results of the range() function.

The tutorial further highlights the brevity and efficiency of list comprehensions, while emphasizing performance considerations. By mastering Python's for loop, professionals can tackle and master many data processes and analytical tasks.

The Basic For Loop Structure

A loop, by its very essence, allows for repeated execution of a sequence of statements, instructions, code, or operations. The for loop in Python is distinctively characterized by its ability to iterate over sequences, be it a list, a string, or DataFrame, the results of the range() function, or another similar object.

A rudimentary example:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

Here, the loop runs three times. On each iteration the look will print each…

Adam Ross Nelson

Ask about my free career course. I mentor new (💫) and aspiring data scientists enter (🚪) and level up (📈) in the field.