Cohort 4Register

PART 1 · PYTHON FROM ZERO · LESSON 15

Functions part 2: lambdas, sorting and building a pipeline

FreeLesson 17 of 78

Functions are values: you can put them in a list, pass them to other functions and chain them. That is how data pipelines are built.

KEY FUNCTIONS AND LAMBDAPYTHON 3.12
products = [("Mouse", 799), ("Hub", 1499),
            ("Pens", 149), ("Lamp", 1199)]

def by_price(item):
    return item[1]

print(sorted(products, key=by_price))
print(sorted(products, key=lambda item: item[1], reverse=True))
print(max(products, key=lambda item: item[1]))

Output

[('Pens', 149), ('Mouse', 799), ('Lamp', 1199), ('Hub', 1499)]
[('Hub', 1499), ('Lamp', 1199), ('Mouse', 799), ('Pens', 149)]
('Hub', 1499)
PARSE, FILTER, SUMMARISE: YOUR FIRST PIPELINEPYTHON 3.12
raw_rows = ["101, Delivered ,1198", "102,cancelled,1999",
            "bad row", "103,  delivered,1499"]

def parse(line):
    parts = line.split(",")
    if len(parts) != 3:
        return None                         # cannot use this row
    order_id, status, amount = parts
    return {"id": int(order_id), "status": status.strip().lower(),
            "amount": float(amount)}

def keep_delivered(rows):
    return [r for r in rows if r and r["status"] == "delivered"]

def summarise(rows):
    revenue = sum(r["amount"] for r in rows)
    return {"orders": len(rows), "revenue": revenue}

rows = [parse(line) for line in raw_rows]          # step 1
clean = keep_delivered(rows)                         # step 2
print(summarise(clean))                              # step 3

Output

{'orders': 2, 'revenue': 2697.0}
ANY NUMBER OF ARGUMENTSPYTHON 3.12
def report(*amounts, currency="Rs"):
    total = sum(amounts)
    print(f"{len(amounts)} orders, total {currency} {total:,}")

report(1198, 796, 1499)
report(1999, currency="INR")

Output

3 orders, total Rs 3,493
1 orders, total INR 1,999

*amounts collects however many values you pass into a tuple. Page 31 covers *args and **kwargs properly.

Try it yourself before moving on

  1. Sort the employees in employees.csv by salary using a lambda.
  2. Add a step to the mini pipeline that drops rows with a duplicate id.
  3. Write average(*numbers) that works for any count of numbers.