The for loop
Now that we have containers, we can present loops.
in essence, the for loop allows the programmer to iterate (to do some repeated action) over the items of an iterable, such as a collection.
Let's start with an example.
# uci_bootcamp_2021/examples/for_loops.py
data = [2, 1, 4, 7, 3]
# loop over the items in `data`.
for item in data:
# `item` refers to the specific element
# and the body of the for loop runs once per value in `data`.
print(item)
# 2
# 1
# 4
# 7
# 3
What happens here is the body of the for loop is run multiple times: once for each value in data.
Each time it runs, item holds a different value, values that come from data. In order.
This loop construct works over
any Iterable, not
just Containers
.
One common anti-pattern beginner python programmers is to loop over range, specifically:
# uci_bootcamp_2021/examples/for_loops.py
collection = [2, 1, 32]
# WARNING: Don't do this! antipattern!
for i in range(len(collection)):
print(i, collection[i])
# 0 2
# 1 1
# 2 32
There is, of course, a better way of writing this in python.
# uci_bootcamp_2021/examples/for_loops.py
# We can also for loop over any iterable, such as enumerate!
for i, item in enumerate(data):
print(i, item)
# 0 2
# 1 1
# 2 4
# 3 7
# 4 3
For loops are powerful constructs for performing operations against a collection or some other iterable. They do not require knowing the length of the iterable (if it has one), or any other details beyond the type of the iterable.