A Guide to Python "For" Loops
Python, like many programming languages, implements containers, which are collections of other objects. As such, Python provides the for
statement for iterating over each element in the collection.
In this guide, we're going to cover the Python for loop. The for statement in Python is slightly different from what you might be used to in other programming languages. But in my opinion, it's easier to work with.
Many languages implement a for loop like this:
for (let i=0; i<someArray.length; i++) {
let element = someArray[i];
// Code to execute for each iteration
}
We have an initialization statement, conditional, and code that executes after the loop (typically to increment or decrement a counter).
But in Python, the structure of the for loop is much simpler:
for item in some_iterable:
# Code to execute for each iteration
The goal of this guide is to provide a comprehensive overview of Python for
loops. We're going to get "in the weeds" at times, and in the end, you should have a good understanding of the various uses of for
loops as well as what's going on under the hood.
In this guide, you'll learn the following:
- What is an iterable?
- How to use the
for
loop to iterate over elements in an iterable. - How to use the
break
,continue
, andelse
statements to control the flow of a for loop. - How to use the
range
function to accomplish common tasks.