25:00
Focus
Lesson 6

Repeating Tasks with For Loops

~11 min100 XP

Introduction

In programming, repeating tasks manually is not only tedious but also prone to human error. By mastering for loops in Python, you will learn how to automate repetitive processes efficiently, allowing your code to handle vast amounts of data with just a few lines of syntax.

Understanding the Iteration Concept

At its core, a for loop is a mechanism for iteration. Imagine you have a list of ten emails you need to send. Instead of writing the "send" command ten times, you define a collection of items and tell the computer: "For every item in this collection, perform this action."

In Python, the for loop works by iterating over a sequence—this could be a list, a tuple, a string, or a range of numbers. When the loop starts, Python assigns the first element of the sequence to a control variable and executes the code block inside the loop. Once finished, it moves to the second element, repeats the process, and continues until it has processed every item in the sequence.

Note: The control variable's name (often i, item, or x) holds no special meaning; however, choosing descriptive names like customer_name or file_path makes your code significantly easier to read and maintain for others.

Exercise 1Multiple Choice
What happens at the end of each iteration in a for loop?

The Power of the range() Function

When you don't necessarily have a list but need to repeat an action a specific number of times—such as printing a "Loading..." message five times—you use the built-in range() function. The range() function generates an immutable sequence of numbers.

Using range(n) generates integers starting from 00 up to, but not including, nn. For instance:

range(5)    {0,1,2,3,4}range(5) \implies \{0, 1, 2, 3, 4\}

This mathematical boundary is a common source of "off-by-one" errors for beginners. If you need a loop to run exactly nn times, ensure you understand that it starts at index 00. If you need to specify a starting point other than 00, you can use range(start, stop). If you need to step by a specific increment, use range(start, stop, step).

Exercise 2True or False
The loop 'for i in range(3):' will execute the internal code block four times.

Nested Loops and Complexity

A nested loop occurs when you place one for loop inside the body of another. This is essential when working with multi-dimensional data, such as a matrix or a grid.

Think of a clock: for every hour that passes (the outer loop), the minute hand must complete a full rotation from 0 to 59 (the inner loop). If you have an outer loop iterating mm times and an inner loop iterating nn times, the total number of operations will be m×nm \times n. Be cautious with deep nesting; while useful, excessive nesting increases the time complexity of your algorithm, which can lead to performance bottlenecks if not managed carefully.

Common Pitfall: Modifying the Collection

A significant mistake many developers make is attempting to add or remove items from a list while iterating over that same list. This can lead to unexpected behavior, as the loop might skip over elements or fall into an unintended state because the internal indices of the collection are shifting while the loop is trying to track its position.

If you need to filter a list, the best practice is to create a new list or use a list comprehension. List comprehensions are a concise way to create lists, effectively combining a for loop and a conditional statement into one readable line of code.

Exercise 3Fill in the Blank
___ are a concise way in Python to create new lists by applying an expression to each item in an existing sequence while optionally filtering the items.

Key Takeaways

  • For loops automate repetitive tasks by iterating over sequences like lists, strings, or numeric ranges.
  • The range() function is exclusive of the stop parameter, meaning range(10) stops at 9, which is crucial for preventing index errors.
  • Nested loops are powerful for multi-dimensional data but increase the computational load of your script.
  • Avoid modifying the list you are currently iterating over; instead, use a new list or a list comprehension to handle transformations safely.
Check Your Understanding

Understanding how for loops manage iteration helps you write cleaner and more efficient code by avoiding manual repetition. Explain the relationship between the sequence, the control variable, and the code block inside the loop, and describe why using a descriptive name for your control variable is better practice than using a generic letter like 'i'.

🔒Upgrade to submit written responses and get AI feedback
Go deeper
  • What happens if the sequence is empty?🔒
  • Can I nest one for loop inside another?🔒
  • How does range() generate numbers differently than a list?🔒
  • Can I modify the sequence while iterating through it?🔒
  • Is there a way to break out of a loop early?🔒