HexLibraryHexLibrary
</> HexCodeSign inSign up
PythonJavaScriptTypeScriptCC++JavaPHPGoRustRubyBashSQLLuaPerlCOBOLPascalDelphiFortranDartSwiftC#JuliaGroovyRElixirHaskellKotlinScalaClassic ASPClipperMS-DOS
LESSONS
Introduction to Python: Print and RepeatVariablesData Types & NumbersStringsListsConditions (if / elif / else)Loops (for / while)FunctionsOperatorsDictionariesTuples & SetsError Handling (try / except)Classes (Object-Oriented)File OperationsComments & IndentationBooleans (True / False)Lambda & map / filterModules (import)InheritanceVariable Scope
REFERENCE
📖 Overview
🖥️ Output & Input
🔢 Numbers & Math
✍️ String
📋 List
🗂️ Dictionary & Set
🔁 Condition & Loop
🧩 Function
📁 File & Error
🔄 Type & Conversion
Python›Lambda & map / filter

Lambda & map / filter

One-line anonymous functions (lambda) and using them with map/filter/sorted.

Simple enough for a 5-year-old to understand

lambda: a one-line function

lambda is a short way to write a small, anonymous function. It returns a single expression.

Example code
1
square = lambda x: x * x
"take x, return its square" — without writing def.
Function"take x, return its square" — without writing def.
2
print(square(5))
Writes 25.
Output / InputWrites 25.
FunctionOutput / Input
💡 Hint: For bigger logic, use a normal def; lambda is for short, single-expression tasks.

🎯 Exercise & Practice

Test what you've learned — answer, write code, check instantly. (1 left)

1.Write a lambda that returns 3 times a number (name: ucKat); print the result of tripleIt(7).

🎯 Expected output: 21

Loading editor…

About this topic

Lambda is a way to write a one-line anonymous function. You write a simple transformation in a single expression that you would normally define in three lines with def. Its name comes from lambda calculus in mathematics and it was brought into Python from functional programming.

The real use case for lambda is when you pass a function as a parameter to another function. When telling the sorted function 'how to sort', filtering with filter, or transforming with map, a small function is needed and giving it a name is unnecessary.

You shouldn't overdo lambda. For logic that doesn't fit into a single expression, contains condition chains, or will be used a second time, writing a normal function is always the better choice.

What you will learn

  • writing one-line functions with lambda
  • sorting using a key function with sorted
  • transforming and filtering with map and filter
  • when list comprehensions are more readable than lambda
  • the limitations of lambda: the single expression rule

When to use?

You will use lambda most often when sorting a list of dictionaries by a field: you give the sorted function a small function that tells it which field to look at. Similarly, criteria can be given to max and min functions.

In contrast, list comprehension is generally preferred over map and filter in Python; it is more readable and doesn't require an extra function call.

Common mistakes

Wrong

f = lambda x:
    if x > 0:
        return "positive"
    return "negative"

Lambda can only take A SINGLE EXPRESSION; it cannot contain an if block, assignment, or multiple lines. This code throws "SyntaxError: invalid syntax". For multi-line logic, def must be used.

Correct

def f(x):
    if x > 0:
        return "positive"
    return "negative"

Wrong

users = [{"name": "Ada", "age": 36}]
users.sort(key=lambda u: u.age)

Dictionaries cannot be accessed with a dot; dot notation is for object attributes. Dictionary keys are read with square brackets, otherwise you get "AttributeError: 'dict' object has no attribute 'age' ".

Correct

users = [{"name": "Ada", "age": 36}]
users.sort(key=lambda u: u["age"])

Wrong

squares = list(map(lambda x: x * x, range(5)))

It works, but it's not the idiomatic way in Python; list comprehension does the same job more concisely and legibly. The combination of map and lambda is a habit brought over from other languages.

Correct

squares = [x * x for x in range(5)]

Frequently asked questions

What is the difference between lambda and def?

Lambda is anonymous, takes a single expression, and automatically returns the result of that expression. def is named, can contain multiple lines, and can take a docstring. Functionally, lambda is a shortcut; def is needed for logic that will be reused or is complex.

Why are we naming a lambda, isn't that pointless?

A fair criticism. If you are assigning a lambda to a variable, you are already giving it a name; in that case, writing def is more correct and the function name appears in error messages. The place for lambda is where it is passed directly as a parameter.

What does key do in sorted?

It determines what each element is compared by. Sorting a list of dictionaries by age, ordering texts by length, or doing case-insensitive sorting is done with key. The function you provide is called once for each element, and the returned value is used in the comparison.

Summary

Lambda is an anonymous function with a single expression, and its main place is providing criteria to functions like sorted and max. When the single expression limit is exceeded or the logic will be reused, writing def is the right choice.

HexLibraryHexLibrary

Learn programming more clearly. Every command is explained line by line with colors, reinforced with runnable exercises, test your code instantly — all in one place, free.

Learn

  • Home
  • Languages & Lessons
  • HexCode

Company

  • About
  • Contact

Legal

  • Privacy Policy
  • Terms of Use

Other Projects

  • HexToolz
  • Free Service Manuals
© 2026 HexLibrary · The clearest way to learn code