Repetition - for loops
Python also provides what is called a for
loops.
In Python, for
loops are useful for iterating over a collection.
The code below is self explanatory and should even read like English.
words = ["I", "have", "a", "dream"]
for word in words:
print(word)
Nested for
loops
Like all building blocks, you can nest a for
loop inside another for loop
.
This is useful if you have a nested list:
matrix = [[1, -2, 3], [-1, 4, 7]]
This is often how you would represent matrices (two dimensional data structures) in Python.
To loop over the elements, use a nested for
loop.
for row in matrix:
print(row)
for entry in row:
print(entry)
To access an arbitrary element in the matrix:
print(matrix[1][0]) # row 1 col 0: value should be -1
for
loops over Dictionaries
for
iterates over the keys in dict
s by default.
height_dict = {"Harry": 163, "Joe": 178, "Will": 182}
for key in height_dict:
print(f"{key}'s weight is {height_dict[key]}")
NOTE: f""
is an f-string (formatted string literal), introduced in Python 3.6 for you to easily format strings with values from variables.
Use the items()
method of dict
to iterate over both keys and values simulataneously.
for (key, value) in height_dict.items():
print(f"{key}'s weight is {value}")
When should I use a for
loop?
Use a for
loop when you are iterating over a fixed collection.
As good programming practice, you should also not modify the list while iterating over the list, e.g. adding or deleting elements while iterating over the list. There will be unintended side-effects!
Consider a while
loop otherwise, where you have more control over the elements in the collection.