Looping Patterns With For Loops
When using for
loops, a few patterns show up frequently. If you learn these patterns — how to recognize them and how to code them —
it can speed up your programming.
The Action Pattern
In the action pattern, we want to do something to (or with) each element of a list.
Here is the pseudocode template:
possible setup code
for each x in xx:
do somethign using x
Example: Printing the Elements of a List
for x in xx:
print(x)
Example: Printing the Elements of a List and Their Squares
for x in xx:
print(f"{x}, {x*x}")
Reading Elements from a File a Printing Them
with open('foo.txt') as file:
for x in file.readlines()
print(x)
Writing Elements of a List to a File
with open('foo.txt','w') as file:
for x in xx:
file.write(f"{x}\n")
The Accumulator Pattern
In the accumulator pattern, we want to build up a pattern using a collection of data.
Here is the pseudocode template:
initialize the accumulator
for each x in xx:
modify accumulator using x
final result is in accumulator
Example: Counting the Elements of a List
For this, count
is the accumulator, and at each step we add one to it.
count = 0
for x in xx:
count = count + 1
Example: Summing the Elements of a List
For this, sum
is the accumulator, and at each step we add x
to it.
sum = 0
for x in xx:
sum = sum + x
Example: Taking the Maximum of the Elements of a List
For this, themax
is the accumulator, and at each step we update it with x
using the built-in funciton max
.
themax = xx[0]
for x in xx[1:]:
themax = max(themax,x)
Note here we initialize themax
to the first element of the list, and iterate over the rest of the elements.
Example: Create a Dictionary with the Elements of a List and Their Squares
For this, d
is the accumulator, and at each step we update it by inserting key x
with value x*x
.
d = {}
for x in xx:
d[x] = x * x
Your turn!
Try to write Python code to
- Take the product of the elements of a list
- Take the minimum of the elements of a list