Lesson 9 of 10

Built-in functions

Goal

Answer data questions in one line

01

Explanation

A lot of loops are written just to answer one question. Does any item meet the condition? Do all of them? Which one is the largest? What's the total? Python has a built-in function for each one, and it answers in a single line that reads like the question itself.

any() returns True if the condition holds for at least one item, and all() returns it if the condition holds for every item. Both stop as soon as they know the answer. max(items, key=...) returns the item with the largest key, not the key itself, just as with sorted.

You pass them a generator expression such as sum(n * n for n in nums). It looks like a list comprehension without the square brackets, and it produces the values one at a time without building a list in memory.

Mind the edge cases: all([]) returns True because no item breaks the condition, and max([]) raises ValueError. If the list might be empty, pass default= to max and min.

02

Your task

Without any loop, compute from products: total_stock, the sum of the quantities; has_out, whether any product is out of stock (its quantity is zero); all_priced, whether every price is positive; priciest, the most expensive product in full; and cheapest_name, the name of the cheapest product.

Checks

6 checks
  1. total_stock is the sum of the quantities
  2. has_out says a product is out of stock
  3. all_priced says every price is positive
  4. priciest is the whole most expensive product, not its price
  5. cheapest_name is the name of the cheapest
  6. Solved with built-ins and generator expressions, with no loop or temporary list
main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/6

Checks start once the environment is ready.

6 checks listed under “Your task”.