runtime
57 / 250
lesson 57 Collection Algorithms · intermediate

Transform every record

A transform builds one new value for every item: a converted reading, a line total, a tidy record. The input stays as it was.

You'll be able to
  • Build a list with exactly one new value per item, in the same order
  • Return new dictionaries instead of writing into the ones you were given
  • Recognise the x = x.append(…) mistake and the error it causes
The idea

A filter decides *which* items to keep. A transform keeps *all* of them and changes their shape: Celsius to Fahrenheit, quantity and price to a line total, a messy record to a tidy one. The result has exactly one value per input item, in the same order.

The loop looks the same. The difference is what you append, and that there is no if deciding whether to append: every pass appends something.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · Celsius to Fahrenheit
celsius = [18.5, 21, -3, 0]
fahrenheit = []
for c in celsius:
    fahrenheit.append(c * 9 / 5 + 32)
print(fahrenheit)
print(celsius)

When the items are dictionaries there is a trap. for item in items gives you the same dictionary that sits inside the list, not a copy. Writing item["amount"] = … would change the caller's data even though you meant to build something new. Build a new dictionary for each item instead, and append that.

example-2.py · Line amounts as new records
def priced_lines(items):
    lines = []
    for item in items:
        amount = item["quantity"] * item["unit_price"]
        lines.append({"product_id": item["product_id"], "amount": amount})
    return lines

items = [
    {"product_id": "P0164", "quantity": 2, "unit_price": 31},
    {"product_id": "P0594", "quantity": 1, "unit_price": 48},
    {"product_id": "P0708", "quantity": 3, "unit_price": 12.5},
]
print(priced_lines(items))
print(items[0])

One more mistake shows up in almost every first transform. append changes the list and gives back None. Storing that result replaces your list with None, and the next pass crashes.

example-3.py · Storing what append returns
labels = []
for name in ["nora", "jamal"]:
    labels = labels.append(name.title())
print(labels)
Review
  • A transform appends exactly one new value per item, in the same order.
  • Build new dictionaries. Assigning into the loop's dictionary changes the caller's data.
  • append changes the list and returns None, so never store its result.
  • Next: instead of one value per item, collect a count, a total or a list under each key.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Transform every record — Collection Algorithms · Runtime