Lambdas In Python

Pavol Kutaj
2 min readFeb 11, 2022

--

The aim of this tutorial🔍 is to introduce anonymous/lambda functions in Python just to make sure they work in the Higher-Order Functions lecture of SICP. You just want a simple callable object without the bureaucratic overhead of

  1. def statement
  2. code block it introduces

Often, an anonymous object is known as lambda (in programming, math, and Python) does the trick. The etymology is covered in Why is lambda calculus named after that specific Greek letter? and, I tend to go with

in Church’s words, the reasoning was “eeny, meeny, miny, moe” — in other words, an arbitrary choice for no reason

— https://math.stackexchange.com/a/2095748

1. PROPERTIES

Unlike lambda forms in other languages, where they add functionality, Python lambdas are only a shorthand notation if you’re too lazy to define a function.

Design and History FAQ — Python 3.9.1 documentation

  • restrictive
  • minimal
  • in python, synonymous with anonymous functions
  • introduce it with lambda instead of def
  • support multiple args
  • constrained to a single expression
lambda args: expression

2. LAMBDA AS FUNCTION EXPRESSION

  • lambda is itself an expression resulting in a callable object
  • lambda can be assigned to a binding and thus actually get a name
  • note that a VScode linter does rephrase this into a function declaration

3. LAMBDA VS DEF KEYWORDS

4. USAGES

  • tiny in size
  • needed for a short time
  • possibly, the content of a lambda itself is more expressive than a potential name
  • usually, they are passed an argument in other functions

5. EXAMPLE: LAMBDA AS PARAMETER FOR HIGHER-ORDER FUNCTIONS (HOF)

  • the HOF summationRecursive from SICP returns the same result for sumInt(a,b) as well as for sumIntLambda(a,b)

6. EXAMPLE: LAMBDA AS PARAMETER / MAP FUNCTION IN SORTED BUILTIN

  • sorted builtin is used for sorting iterable series
  • the optional key argument must be a callable
sorted(<iterable>,key=<callable>)
  • the key works as a mapping function that transforms the iterable as required
  • that lambda name: name.split()[-1] does is a mapping function to transform individual list items+
  • …and sorting will be done based on the transformed values, in the example above you are sorting
"turing", "gates"

7. SOURCES

--

--

No responses yet