For Loops
Contents
For Loops#
A while loop continues for as long as a condition is met, a for loop on the
other hand repeats for every element in an iterable.
Table of Contents
Part 1: Syntax#
The syntax for a for loop is:
for VAR in ITERABLE:BODY
|
variable name (or comma-separated list of names) to assign each item to |
|
object to iterate over. |
|
statements to execute where |
Here’s a simple example that iterates over a list of strings.
1for word in ["apple", "banana", "cherry"]:
2 letter = word[0].upper()
3 print(f"{letter} is for: {word}.")
Part 1.1: Exercise#
Exercise 29 (Movies)
Iterate over a list of movies and print each one out using a for loop.
Solution to Exercise 29 (Movies)
1movies = [
2 "Treasure Planet",
3 "Finding Nemo",
4 "Kung Fu Panda",
5 "Wall-E",
6 "Lilo & Stitch",
7]
8
9for name in movies:
10 print(movie)
Part 2: Iterables and iterators#
Some objects in Python are iterable–that is, an object that can be
iterated over. For example, list, tuple and range objects are all
iterable.
All iterables can be converted to an iterator, which is an object that will keep returning elements until there are no more left.
To demonstrate this we’ll create a colors list then convert the it to a
colors_iterator using the iter() function.
colors = ["red", "green", "blue"]
colors_iterator = iter(colors)
Then we’ll keep requesting items using the next() function, until we
encounter a StopIteration exception.
next(colors_iterator)
'red'
next(colors_iterator)
'green'
next(colors_iterator)
'blue'
next(colors_iterator)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
Cell In[5], line 1
----> 1 next(colors_iterator)
StopIteration:
Part 2.1: Exercise#
Exercise 30 (Iterators)
Create a list containing the letters in your name assigned to the variable
letters.Convert the list to an iterator using the
iter()function and assign it to the variableletters_iterator.Keep calling
next()with the argumentletters_iteratoruntil you encounter aStopIterationexception.
Solution to Exercise 30 (Iterators)
>>> letters = list("alissa")
>>> letters_iterator = iter(letters)
>>> next(letters_iterator)
'a'
>>> next(letters_iterator)
'l'
>>> next(letters_iterator)
'i'
>>> next(letters_iterator)
's'
>>> next(letters_iterator)
's'
>>> next(letters_iterator)
'a'
>>> next(letters_iterator)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-51-15be8840759d> in <module>
----> 1 next(letters_iterator)
Part 3: Under the hood#
Now that you know what iterables and iterators are, we demystify for loops.
Lets look at the syntax again.
for VAR in ITERABLE:BODY
Here’s what’s happening behind the scenes:
ITERABLEis converted to an iterator object usingiter(), or rather its magic methodEach iteration,
next()is called, and the results are assigned toVARThe
BODYstatements are executedWhen
next()results in aStopIterationexception it is discarded and the loop ends
Lets revisit our for loop example, and see if we can deconstruct the behavior
of a for loop. First we’ll create a houses list, and convert it to a
houses_iter using the iter() function.
# create iterable
houses = [
"Arryn",
"Baratheon",
"Greyjoy",
"Lannister",
"Martell",
"Stark",
"Targaryen",
"Tully",
"Tyrell",
]
# create iterator
houses_iter = iter(houses)
Now we’ll call next() in a while loop, and assign the results to name.
# loop forever
while True:
# assign VAR to the results of next()
name = next(houses_iter)
# BODY statements
print(f"House {name}")
House Arryn
House Baratheon
House Greyjoy
House Lannister
House Martell
House Stark
House Targaryen
House Tully
House Tyrell
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
Cell In[7], line 4
1 # loop forever
2 while True:
3 # assign VAR to the results of next()
----> 4 name = next(houses_iter)
6 # BODY statements
7 print(f"House {name}")
StopIteration:
This is close, but we’re still seeing that StopIteration exception. To
suppress it we’ll need a try-except block.
# create iterator
houses_iter = iter(houses)
# loop forever
while True:
# any code that may raise an exception goes under the try header
try:
# assign VAR to the results of next()
name = next(houses_iter)
# the type of exception that we want to catch
# instead of raising it, the body statements will be executed
except StopIteration:
# StopIteration means there are no more elements, so exit the loop
break
# BODY statements
print(f"House {name}")
House Arryn
House Baratheon
House Greyjoy
House Lannister
House Martell
House Stark
House Targaryen
House Tully
House Tyrell
Now we have a while loop that replicates the behavior of a for loop. Here they are side by side.
houses = [
"Arryn",
"Baratheon",
"Greyjoy",
"Lannister",
"Martell",
"Stark",
"Targaryen",
"Tully",
"Tyrell",
]
houses_iter = iter(houses)
while True:
try:
name = next(houses_iter)
except StopIteration:
break
print(f"House {name}")
houses = [
"Arryn",
"Baratheon",
"Greyjoy",
"Lannister",
"Martell",
"Stark",
"Targaryen",
"Tully",
"Tyrell",
]
for name in houses:
print(f"House {name}")
Part 3.1: Exercise#
Exercise 31 (Game Characters)
Make a
listof game characterroles.write a
whileloopConvert the
listto anroles_iteriterator using theiter()functionMake a
whileloop with the conditionTrueGet each
roleelement from theroles_iterby callingnext()Print the
roleSuppress the error with a try-except block
write a
forloopMake a
forloop with the variable nameroleand the iterablerolesPrint the
role
Solution to Exercise 31 (Game Characters)
1WIDTH = 30
2roles = ["mage", "thief", "warrior"]
3
4print("WHILE LOOP ".ljust(WIDTH, "#"))
5roles_iterator = iter(roles)
6while True:
7 try:
8 role = next(roles_iterator)
9 except StopIteration:
10 break
11 print(role)
12
13
14print("FOR LOOP ".ljust(WIDTH, "#"))
15for role in roles:
16 print(role)
Part 4: Multiple assignment#
Depending on the type passed to it, next() may sometimes return more than one
value. The classic example of this is dict.items().
suites = {
"heart": "red",
"diamond": "red",
"club": "black",
"spade": "black",
}
suites_iterator = iter(suites.items())
next(suites_iterator)
('heart', 'red')
You can see that next() returns a tuple that contains two items. We can
assign this to a single variable, which will then contain the entire tuple.
item = next(suites_iterator)
item
('diamond', 'red')
Or we could use multiple assignment to assign each item in the tuple
to a corresponding variable. There must be the same number of variables to the
left of the = as there are items in the tuple separated by ,.
suit, color = next(suites_iterator)
suit
'club'
color
'black'
Lets put this assignment fanciness in a while loop.
suites_iterator = iter(suites.items())
while True:
try:
suit, color = next(suites_iterator)
except StopIteration:
break
print(f"The {suit} suit is {color}.")
The heart suit is red.
The diamond suit is red.
The club suit is black.
The spade suit is black.
And lets see how it looks in a for loop.
for suit, color in suites.items():
print(f"The {suit} suit is {color}.")
The heart suit is red.
The diamond suit is red.
The club suit is black.
The spade suit is black.
Here they are side by side.
1suites = {
2 "heart": "red",
3 "diamond": "red",
4 "club": "black",
5 "spade": "black",
6}
7
8suites_iterator = iter(suites.items())
9
10while True:
11 try:
12 suit, color = next(suites_iterator)
13 except StopIteration:
14 break
15
16 print(f"The {suit} suit is {color}.")
1suites = {
2 "heart": "red",
3 "diamond": "red",
4 "club": "black",
5 "spade": "black",
6}
7
8for suit, color in suites.items():
9 print(f"The {suit} suit is {color}.")
Part 4.1: Exercise#
Exercise 32 (Game Tools)
Make a
dictof game charactertools, where the key is theroleand the value is atool.write a
whileloopConvert
tools.items()to antools_iteriterator using theiter()functionMake a
whileloop with the conditionTrueGet each
roleandtoolelement from thetools_iterby callingnext()Print the
"A roles favorite tool is their trusty: tool."Suppress the error with a try-except block
write a
forloopMake a
forloop with the variable nametooland the iterabletoolsPrint the
tool
Solution to Exercise 34 (Game Skills)
1WIDTH = 30
2tools = {
3 "mage": "wand",
4 "thief": "lockpick set",
5 "warrior": "sword",
6}
7tools_iter = iter(tools.items())
8
9print("WHILE LOOP ".ljust(WIDTH, "#"))
10while True:
11 try:
12 role, tool = next(tools_iter)
13 except StopIteration:
14 break
15 print(f"A {role}s favorite tool is their trusty: {tool}.")
16
17print("FOR LOOP ".ljust(WIDTH, "#"))
18for role, tool in tools.items():
19 print(f"A {role}s favorite tool is their trusty: {tool}.")
Part 5: Incrementing#
Sometimes we need to keep track of the number associated with each item in an iterable. One way to do this would be to increment a number each iteration.
i = 0
rainbow = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]
for color in rainbow:
print(i, color)
i += 1
0 red
1 orange
2 yellow
3 green
4 blue
5 indigo
6 violet
An easier way to do this is to use the enumerate() function which returns an
iterator. Each iteration it yields a tuple containing the count and the next
item.
Lets take a look at what happens when we pass the rainbow list to
enumerate(). (Notice that we convert the iterator to a list so we can see its
contents.)
list(enumerate(rainbow))
[(0, 'red'),
(1, 'orange'),
(2, 'yellow'),
(3, 'green'),
(4, 'blue'),
(5, 'indigo'),
(6, 'violet')]
To use this in a for loop, we’ll call enumerate() on the ITERABLE. Then
we’ll change VAR so that it assigns both i and color.
rainbow = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]
for i, color in enumerate(rainbow):
print(i, color)
0 red
1 orange
2 yellow
3 green
4 blue
5 indigo
6 violet
We can change the number that emumerate() starts at by passing an optional
second argument.
rainbow = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]
for i, color in enumerate(rainbow, 1):
print(i, color)
1 red
2 orange
3 yellow
4 green
5 blue
6 indigo
7 violet
But what happens if you want to enumerate an iterable that yields multiple items per iteration? Is it possible to assign the number and the other items to their respective variable names?
Lets take a look at what happens when we pass a dict.items() treatable to
enumerate().
suites = {
"heart": "red",
"diamond": "red",
"club": "black",
"spade": "black",
}
list(enumerate(suites.items()))
[(0, ('heart', 'red')),
(1, ('diamond', 'red')),
(2, ('club', 'black')),
(3, ('spade', 'black'))]
The iterable now yields a tuple containing the count, and each item is a
tuple containing the key and value like so: (COUNT, (KEY, VALUE))
To use this in a for loop, simply enclose the key-value tuple in parenthesis.
suites = {
"heart": "red",
"diamond": "red",
"club": "black",
"spade": "black",
}
for i, (suit, color) in enumerate(suites.items(), 1):
print(f"{i}. The {suit} suit is {color}.")
1. The heart suit is red.
2. The diamond suit is red.
3. The club suit is black.
4. The spade suit is black.
Part 5.1: Exercise#
Exercise 33 (Number Names)
Use the enumerate function to print the numerical values 1 through 5 next
to the names of those numbers ("one" through "five").
Need help?
Make a list assigned to the variable
numberscontaining the names of the numbers"one"through"five".Write a
forloop using the variable namesiandnamethat iterates over the value returned from callingenumerate()with the argumentsnumbersand1.
In the for loop:print
iandname
Example output:
1 one
2 two
3 three
4 four
5 five
Solution to Exercise 33 (Number Names)
1numbers = ["one", "two", "three", "four", "five"]
2
3for i, name in enumerate(numbers, 1):
4 print(i, name)
Part 6: Comparing loops#
Lets do some side-by-side comparisons of the same code written as a while loop
and a for loop.
On the left will be the while loop code and on the right will be the for loop code.
Part 6.1: list iteration with next()#
In this example we’ll iterate over a colors list.
On the left we will use a while loop to iterate over a list by converting
it using the iter() function, then calling next() on the resulting
iterator.
On the right the same code as a for loop, where the use of iter() and
next() happens behind the scenes.
colors = ["red", "green", "blue"]
colors_iterator = iter(colors)
while True:
try:
color = next(colors_iterator)
except StopIteration:
break
print(color)
colors = ["red", "green", "blue"]
for color in colors:
print(color)
Part 6.2: range iteration with next()#
Lets do the same comparison with a range object.
On the left we will use a while loop to iterate over a range by converting
it using the iter() function, then calling next() on the resulting
iterator.
On the right is the same code as a for loop.
numbers = range(1, 4)
numbers_iter = iter(numbers)
while True:
try:
num = next(numbers_iter)
except StopIteration:
break
print(num)
numbers = range(1, 4)
for num in numbers:
print(num)
Part 6.3: list iteration with subscription#
In this example we’ll iterate over the colors list as before, except now
we’ll use an incrementing index number to get each element using
bracket notation or subscription.
While you can achieve similar results this way, subscription is not a perfect
mirror of an analogous for loop. It’s not quite as accurate in terms of what
goes on under the hood and in fact not all iterable objects provide access via
bracket notation.
Even so, the this familiar pattern may help to shed some light on for loop
behavior.
colors = ["red", "green", "blue"]
idx = 0
while idx < len(colors):
color = colors[idx]
print(color)
idx += 1
colors = ["red", "green", "blue"]
for color in colors:
print(color)
Part 6.4: string iteration with subscription#
In this example we’ll iterate over each letter in the string word using
bracket notation.
Part 7: Exercises#
Part 7.1: Game Skills#
Exercise 34 (Game Skills)
Make a
listof game characterskills.write a
whileloopAssign the
idxvar to0Make a
whileloop with the condition thatidxis less than the length ofskillsGet each element from
skillsusing bracket notationidxand assign it toskillIncrement
idxPrint the
skill
write a
forloopMake a
forloop with the variable nameskilland the iterableskillsPrint the
skill
Solution to Exercise 34 (Game Skills)
1WIDTH = 30
2skills = ["heal", "attack", "acquire"]
3idx = 0
4
5print("WHILE LOOP ".ljust(WIDTH, "#"))
6while idx < len(skills):
7 skill = skills[idx]
8 print(skill)
9 idx += 1
10
11print("FOR LOOP ".ljust(WIDTH, "#"))
12for skill in skills:
13 print(skill)
Part 7.2: Weekdays#
Exercise 35 (Weekdays)
Print the weekday names horizontally and seperated by |.
Make a
WEEKDAYSlistof names.Use a
forloop to iterated over eachday.Print each
daycentered to the samesize(somewhere around10to20) with seperated by vertical bars (|).
Hint: using the.center()method.
Example output:
| Monday | Tuesday | Wednesday | Thursday | Friday |
Solution to Exercise 35 (Weekdays)
1SIZE=10
2SEP = " | "
3WEEKDAYS = [
4 "Monday",
5 "Tuesday",
6 "Wednesday",
7 "Thursday",
8 "Friday",
9]
10
11strings = [SEP]
12
13for day in WEEKDAYS:
14 title = day.center(SIZE)
15 strings = strings + [title, SEP]
16
17print(*strings, sep="")
Reference#
Glossary#
For Loops#
- iterable#
An object that can be iterated over. One that provides the
.__iter__()method used by theiter()function.- iterator#
An object that provides a
.__next__()method, used by the built in functionnext(), which, when called repeatedly, will keep returning elements until there are no more left.- multiple assignment#
Assigning the contents of an itrable to multiple variables on the same line with the same number of variables names to the left of the
=as there are items in the iterable seperated by,.
For example:
from, to = (1, 100)
first, last = "a", "b"
See also#
See also