operator, frozen data and partial
Sort the products by name instead, with attrgetter('name'). Then try itemgetter(0) on the rows.
Functional style means building programs from small pure functions that take values and return new values, instead of changing things in place. Python mixes it freely with other styles: map, filter, reduce, comprehensions, operator and immutable data are its tools.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 6 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
Write a pure function double_all(numbers) that returns a new list with every number doubled, without changing the input. Show that the input is unchanged.
Sort [("pen", 10), ("bag", 120), ("book", 250)] by the price (second item) from highest to lowest using operator.itemgetter.
Use reduce and operator.mul to compute the product of [2, 3, 4], then do the same with math.prod (a built-in helper that multiplies all the numbers in a list) and compare.
Explain it without notes
What is a pure function and what are its benefits?
When would you choose a comprehension over map and filter, and when the reverse?
Why does list.sort() return None, and what is the functional alternative?
What do operator.itemgetter and operator.attrgetter do?
Expected output
[Product(name='pen', price=10), Product(name='bag', price=120), Product(name='book', price=250)]
['a', 'bb', 'ccc']
[('Grace', 45), ('Ada', 36), ('Linus', 28)]
operator.add: 10
operator.mul: 24
Product(name='pen', price=10) Product(name='pen', price=8)
FrozenInstanceError
[2, 4, 6]