25:00
Focus
Lesson 7

Iterating Through Data with For Loops

~12 min100 XP

Introduction

Mastering loops is the gateway to moving from writing static scripts to building dynamic, automated programs. By the end of this lesson, you will understand exactly how to harness the power of for loops to process entire datasets with just a few lines of code.

Anatomy of a For Loop

At its core, a for loop is a control flow statement that allows you to execute a block of code repeatedly for each item in a sequence. In Python, an iterable is any objectβ€”like a list, tuple, or stringβ€”that you can loop over. When you write a for loop, you are essentially telling the computer: "For every element inside this collection, do these specific tasks."

The syntax is clean and readable: for item in sequence:. The item is a variable name you choose; it acts as a temporary placeholder for the current element being processed. The sequence is the data structure containing your elements. A common pitfall for beginners is forgetting the colon (:) at the end of the loop header or misaligning the indentation of the code block that follows. In Python, the code inside the loop must be indented, as this whitespace defines the scope of the loop. If your code is not properly indented, Python will throw an IndentationError, preventing your program from running.

Exercise 1Multiple Choice
Which part of the 'for' loop syntax is responsible for defining the block of code that runs repeatedly?

Processing Lists with Loops

Lists are the most common containers for data in Python. Using a for loop to process a list allows you to perform operations like calculating sums, formatting strings, or filtering specific data points. Imagine you have a list of prices and you want to apply a discount to each one. Instead of writing the same line of code multiple times, you write the logic once and let the loop handle the iteration.

When iterating, you can also combine the loop with conditional logic, such as if statements, to filter your data. This is often called filtering the iterable, where the code only acts on items that meet certain criteria.

The Power of the Range Function

Sometimes, you don't have a pre-existing list, but you want to run a loop a specific number of times. This is where range() comes in. The range() function generates a sequence of numbers, which is technically a special type of object in Python. The most common form is range(n), which generates numbers from 00 to nβˆ’1n-1.

You can also provide a start and stop point using range(start, stop). If you need to jump by intervals, you can include a third argument: range(start, stop, step). Using range is essential when you need to track the index of your items during iteration, rather than just the items themselves.

Exercise 2Fill in the Blank
If you write 'for i in range(5):', the variable 'i' will take on a maximum value of ___ .

Tracking Indices with Enumerate

A common challenge arises when you need to know the index (the position) of an item while you are iterating. You could use range(len(list)), but there is a more "Pythonic" approach: the enumerate() function. enumerate() takes an iterable and returns it as a series of pairs containing the index and the value.

This is particularly useful when you need to update a list or print formatted labels that include the position number. It eliminates the need for manual counter variables, making your code cleaner and less prone to off-by-one errors.

Exercise 3True or False
The 'enumerate()' function allows you to access both the index and the element value during each iteration of a for loop.

Nested Loops and Complexity

A nested loop is simply a loop inside another loop. These are useful when you are dealing with multidimensional data, such as a list of lists (a matrix). When you nest loops, the inner loop completes its entire cycle for every single iteration of the outer loop.

While powerful, nested loops can lead to performance issues if your data sets are very large. Mathematically, if an outer loop runs NN times and an inner loop runs MM times, the total number of operations grows as NΓ—MN \times M. If N=100N=100 and M=100M=100, you are performing 10,00010,000 operations. Always consider if there is a more efficient way to process the data before reaching for a nested structure.

Exercise 4Multiple Choice
If you have a list containing 5 sub-lists, each with 3 items, how many times will a nested loop print a value?

Key Takeaways

  • Use for item in sequence: to process elements in a collection efficiently.
  • Always use correct indentation to define your loop block; it is non-negotiable in Python.
  • The range() function is your go-to tool for running loops a specific number of times.
  • Employ enumerate() when you need to keep track of the index of an item alongside its value.
  • Be cautious with nested loops, as their efficiency decreases significantly as the input size grows.
Finding tutorial videos...
Go deeper
  • What counts as an iterable besides lists, tuples, and strings?πŸ”’
  • What happens if I forget to indent the code block?πŸ”’
  • How do I loop through a dictionary using this syntax?πŸ”’
  • Can I nest one for loop inside another loop?πŸ”’
  • How does the 'range' function work with for loops?πŸ”’