Transforming Collections

Lesson 52 of 54 · Python Foundations

Building a fresh list keeps the original list unchanged. This function selects values whose exact type is int rather than converting text into numbers.

def only_integers(values: list[object]) -> list[int]:
    result: list[int] = []
    for value in values:
        if type(value) is int:
            result.append(value)
    return result

items: list[object] = ["3", 3, 2.5, True, 8]
print(only_integers(items))
print(items)
[3, 8]
['3', 3, 2.5, True, 8]

The exact-type choice excludes True, even though Python considers bool a subclass of int and isinstance(True, int) is true. Choose isinstance when subclasses should count. The string "3" stays a string; no conversion occurs. Static checkers differ in how well they narrow types through an exact type(...) is ... test.

A different transformation divides every value, preserving order and producing floats. Reject zero even for an empty list so the rule is consistent.

def scaled(values: list[int], divisor: int) -> list[float]:
    if divisor == 0:
        raise ValueError("divisor must not be zero")
    result: list[float] = []
    for value in values:
        result.append(value / divisor)
    return result

original = [9, 12, 15]
print(scaled(original, 3))
print(original)
[3.0, 4.0, 5.0]
[9, 12, 15]

/ produces floating-point results; no rounding is performed. Floating-point arithmetic may not represent every decimal exactly.

Comparing a checklist

Suppose a kit needs several items. We can collect the missing items and calculate what percentage of the required entries are present:

required = ["water", "torch", "map", "radio"]
packed = ["water", "map", "radio"]
missing = []
for item in required:
    if item not in packed:
        missing.append(item)

matched = len(required) - len(missing)
percentage = matched / len(required) * 100 if required else 100.0
print(missing)
print(percentage)
['torch']
75.0

For each required entry, membership checks whether that value appears in packed. Three of the four entries match, so the result is 75 percent. The expression value_if_true if condition else value_if_false selects one of two values. Here required is truthy when nonempty, so Python calculates the percentage; otherwise it selects 100.0 without evaluating the division. This avoids division by zero, but is a policy choice for this example, not a universal rule. It counts entries rather than quantities, so repeated requirements would need a different approach when quantities matter.