← Intro to programming with Python

Loop patterns: finding the biggest and building strings

Keep the best so far, and grow a result piece by piece.

Start this lesson

Two more patterns. To find the biggest value, keep a "best so far": start with the first item, then look at each item and replace the best whenever you find a bigger one. It is how you would find the tallest person in a line, one person at a time. To build a string, start with an empty string "" and add a piece each time round the loop.

temps = [18, 24, 21, 27, 19]
hottest = temps[0]
for t in temps:
    if t > hottest:
        hottest = t
print(hottest)      # 27

stars = ""
for word in ["sun", "moon", "star"]:
    stars += word[0]
print(stars)        # sms

hottest only changes when a bigger value turns up. stars grows by one letter each time.

Common mistake: starting hottest at 0. If every value is negative (like winter temperatures), 0 would wrongly win. Start with the first item instead.

Python also has max() and min() built in. Knowing the pattern still matters, because you will often need "the best so far" for things max() cannot do directly.