Python 101 - The for Loop
There are many times when you are writing code that you will need to process each object in a collection. In order to do that you will iterate over that collection, which means getting each object from that collection one at a time. Collections of objects include strings such as “Hello, world”, lists like [1, 2, 3], and even files. The process of iterating over something is done via a loop, and objects that support being iterated over are called iterables.
In Python, there are two types of loop constructs:
The
forloopThe
whileloop
Besides iterating over sequences and other collections, you can use a loop to do the same thing multiple times. One example of this is a web server: it waits, listening for a client to send it a message; when it receives the message, the code inside the loop will call a function in response.
Another example is the game loop. When you beat a game or lose a game, the game doesn’t usually exit. Instead, it will ask you if you want to play again. This is done by wrapping the entire program in a loop.
In this tutorial you will learn how to:
Create a
forloopLoop over a string
Loop over a dictionary
Extract multiple values from a tuple
Use
enumeratewith loops
You will learn about Python’s while loop in next week’s issue. This week, you will focus on the for loop.
Let’s get started!
Creating a for Loop
The for loop is the most popular looping construct in Python. A for loop is created using the following syntax:
for x in iterable:
# do somethingNow the code above does nothing. So let’s write a for loop that iterates over a list, one item at a time:
In this code, you create a list with three integers in it. Next you create a for loop that says “for each item in my list, print out the item”.
Of course, most of the time you will actually want to do something to the item. For example, you might want to double it:
Or you might want to only print out only the even-numbered items:
Here you use the modulus operator, %, to find the remainder of the item divided by 2. If the remainder is 0, then you know that the item is an even number.
You can use loops and conditionals and any other Python construct to create complex pieces of code that are only limited by your imagination.
Let’s learn what else you can loop over besides lists.
Looping Over a String
One of the differences of the for loop in Python versus other programming languages is that you can iterate over any collection. So you can iterate over many data types.
Let’s look at iterating over a string:
This shows you how easy it is to iterate over a string.
Now let’s try iterating over another common data type!
Looping Over a Dictionary
Python dictionaries also support looping. By default, when you loop over a dictionary, you will loop over its keys:
You can loop over both the key and the value of a dictionary if you make use of its items() method:
In this example, you specify that you want to extract the user and the password in each iteration. As you might recall, the items() method returns a view that is formatted like a list of tuples. Because of that, you can extract each key: value pair from this view and print them out.
Note that you should not modify a dict while looping over it. Instead, you should create a copy and loop over the copy while modifying the original.
This leads us to looping over tuples and getting out individual items from a tuple while looping!
Extracting Multiple Values in a Tuple While Looping
Sometimes you will need to loop over a list of tuples and get each item within the tuple. It may sound unusual, but you will find that it is a reasonably common programming task.
To get this to work, you take advantage of the fact that you know each tuple has two items in it. Since you know the format of the list of tuples ahead of time, you know how to extract the values.
If you hadn’t extracted the items individually from the tuples, you would have ended up with this kind of output:
This is probably not what you expected. You will usually want to extract an item from the tuple or perhaps multiple items, rather than extracting the entire tuple.
Now let’s discover another useful way to loop!
Using enumerate with Loops
Python comes with a built-in function called enumerate. This function takes in an iterable, like a string, list, or set, and returns a tuple in the form of (count, item). The first value of count is 0 because, in Python, counting starts at zero. If the iterable is a sequence, like a string or list, then count is also the position of the item returned.
Here’s an example:
Nice! You should try usin enumerate with some other data types to see how the output changes.
Wrapping Up
Loops are very helpful for iterating over data.
Specifically, you learned about the following topics:
Creating a
forloopLooping over a string
Looping over a dictionary
Extracting multiple values from a tuple
Using
enumeratewith loops
With a bit of practice, you will soon become quite adept at using loops in your own code!










