Numbers and text in loops

Lesson 36 of 54 · Python Foundations

A loop can maintain a running result. For a maximum, starting with the first actual reading works even when every number is negative. Handle an empty list separately because it has no first reading.

def highest(values):
    if not values:
        return None
    best = values[0]
    for value in values[1:]:
        if value > best:
            best = value
    return best

print(highest([-8, -3, -6]))
print(highest([]))
-3
None

best moves from -8 to -3 and remains there. The built-in max(values) does this comparison too, but raises ValueError for an empty list unless given a default. Another possible initial value is float("-inf"), negative infinity; deciding what an empty input should return remains a separate design choice.

The % operator gives the remainder associated with floor division. With a positive divisor, number % 2 is 0 for even integers and 1 for odd integers, including negative integers.

numbers = [-3, 2, 5, 8]
odds = []
for number in numbers:
    if number % 2 != 0:
        odds.append(number)
print(odds)
[-3, 5]

Strings can be split into words and joined again. split() without an argument splits on whitespace, discarding runs of whitespace; join puts its separator between strings.

message = "  rain   then sun "
words = message.split()
kept = []
for word in words:
    if word != "then":
        kept.append(word)
print(words)
print(" ".join(kept))
['rain', 'then', 'sun']
rain sun

An explicit separator behaves differently from whitespace splitting:

record = "red,,blue,"
fields = record.split(",")
print(fields)
print("|".join(fields))
['red', '', 'blue', '']
red||blue|

Each comma marks a boundary. Adjacent commas and the final comma leave empty fields, which join retains between the new separators. This simple split is not a CSV parser: quoted commas need a CSV-aware reader.

The comparison above matches complete, case-sensitive tokens. Punctuation stays attached, so this is not a general-purpose text filter; splitting and joining also changes whitespace.