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.
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.
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.
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 to .
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.
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.
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 times and an inner loop runs times, the total number of operations grows as . If and , you are performing operations. Always consider if there is a more efficient way to process the data before reaching for a nested structure.
for item in sequence: to process elements in a collection efficiently.range() function is your go-to tool for running loops a specific number of times.enumerate() when you need to keep track of the index of an item alongside its value.