for
Loops
One of the defining features of computers is their ability to perform repetitive tasks with
precision and speed. Python, like many other languages, offers powerful construct known as
the for
loop to automate and simplify such repetitive actions.
What is a for
Loop?
A for
loop is a programming structure that enables you to execute a specific code block
repeatedly. It iterates over a sequence of items, performing the same actions for each item.
Whether you want to process a list of values, manipulate strings, or iterate over the elements
of a dictionary, the for
loop is a go-to tool.
Basic Structure of a For Loop
In Python, a for
loop is defined using the for keyword, followed by a variable (often called
an iterator) that represents each item in the sequence, the in keyword, and the sequence itself.
The indented code block immediately following the for statement defines what you want to do with
each item in the sequence.
Would return:
Using For Loops with Lists
See Also
One common use case for for
loops is iterating over lists. Lists are collections of data elements,
and you can effortlessly process each element in the list using a for
loop. Here’s an example:
For Loop Iterating Over a List | |
---|---|
Results in:
In the above code, the for
loop iterates over the fav_books
list, converting each book title to
title case and printing it.
For Loops and the range()
Function
for
loops can also work in tandem with the range()
function, which generates a sequence of
numbers. This is particularly useful when you must repeat an action a specific number of times.
However, it’s essential to remember that range()
generates numbers up to, but not including
the specified end value. Here’s an example:
Returns:
This code snippet will print numbers from 1 to 10, emphasizing the importance of being mindful of the common “off by one” error.
Looping Over Dictionaries
See Also
Python’s for
loop can efficiently iterate over dictionaries
(the dict
object)as well. Dictionaries are collections
of key-value pairs, and you can loop over their keys, values, or both. Lets start with a
basic dict
of names (keys) and phone numbers (values):
Basic Dictionary | |
---|---|
Looping over the keys is the default behaviour, so it is possible to use for
name in phone_numbers:
. However, being a bit more explicit is recommended:
Iterating Over Dictionary Keys | |
---|---|
It is also possible to loop over the values of a dict
object:
Iterating Over Dictionary Values | |
---|---|
Which would return:
Depending on the use case, it might also be necessary to return both the keys and the values of
a dict
object:
Iterating Over Dictionary Items (Key and Value) | |
---|---|
Resulting with:
Tip
Note that dict.items()
returns a tuple
so we unpack it
by using two variables in the for
loop.