What is Lambda?

Lambda is a short way to write a small, unnamed function directly in your code. It lets you create a quick piece of reusable logic without giving it a formal name.

Let's break it down

  • Lambda: a Greek letter used in math and computer science to represent an anonymous function.
  • Short way: a compact syntax that takes fewer characters than a full function definition.
  • Small, unnamed function: a piece of code that does something (like add two numbers) but doesn’t have a name you have to declare elsewhere.
  • Directly in your code: you write it right where you need it, instead of defining it somewhere else first.
  • Reusable logic: you can call it multiple times, just like any other function.
  • Without giving it a formal name: you don’t have to think up a name; the function lives only as a temporary value.

Why does it matter?

Lambdas make code shorter and clearer, especially when you need a simple operation only once or as a quick argument to another function. They help keep your programs tidy and reduce the amount of boilerplate you have to write.

Where is it used?

  • Sorting a list of objects by a specific field (e.g., list.sort(key=lambda x: x.age)).
  • Filtering data in a collection, such as filter(lambda x: x > 10, numbers).
  • Defining short callbacks for UI events or asynchronous tasks.
  • Passing simple calculations to higher-order functions like map, reduce, or sorted.

Good things about it

  • Concise syntax saves typing and visual clutter.
  • Perfect for one-off functions that don’t need a full definition.
  • Works well with higher-order functions, enabling functional-style programming.
  • Keeps related logic close to where it’s used, improving readability.
  • Often faster to write and prototype than full functions.

Not-so-good things

  • Can become hard to read if over-used or made too complex.
  • Limited to single expressions in many languages, so they can’t contain multiple statements.
  • Debugging may be trickier because they lack a descriptive name.
  • Some languages restrict features (e.g., no annotations or docstrings) inside lambdas.