Defining lambdas

A lambda form is a degenerate kind of function. A lambda doesn't even have a name: it has only parameters and a single expression. We create a lambda by providing the parameter names and the expression. It looks like this:

lambda x: x[0]+x[1]

This kind of thing is helpful in the context of Python's higher-order functions. We often use lambdas with max(), min(), sorted(), map(), filter(), or list.sort(). Here's a simple example:

>>> colors = [ ... (255,160,137), ... (143, 80,157), ... (255,255,255), ... (162,173,208), ... (255, 67,164), ... ] >>> sorted(colors) [(143, 80, 157), (162, 173, 208), (255, 67, 164), (255, 160, 137), (255, 255, 255)] >>> sorted(colors, ... key= lambda rgb: (rgb[0]+rgb[1]+rgb[2])/3) [(143, 80, 157), (255, ...

Get Python Essentials now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.