CodingNic

Functions and Reusability

Lambda Functions

Functions and Reusability 20 min read

Lambda Functions

Lambda Functions

Sometimes you need a small function for a quick task.

Instead of writing a full function with def, Python gives a shorter way.

This is called a lambda function.

What Is a Lambda Function?

A lambda function is a small one-line function.

It is useful for simple actions.

Normal Function Example

python
def double(number):
    return number * 2

print(double(5))

Output

text
10

Same Example with Lambda

python
double = lambda number: number * 2

print(double(5))

Output

text
10

How It Works

python
lambda number: number * 2

Let’s break it down:

  • lambda starts the function
  • number is the input value
  • : separates input from result
  • number * 2 is the returned result

Why Use Lambda?

Use lambda when:

  • The task is short
  • You need a quick function
  • You do not want a full def block

Another Example

python
add = lambda a, b: a + b

print(add(3, 7))

Output

text
10

With Sorted Data (Simple Example)

python
names = ["Tom", "Anna", "Mike"]

names.sort(key=lambda name: len(name))

print(names)

Output

text
['Tom', 'Mike', 'Anna']

The names are sorted by length.

When Not to Use Lambda

Do not use lambda for large or complex code.

Use normal functions when the logic needs many lines.

Code Along

python
square = lambda number: number * number

print(square(4))

Output

text
16

Mini Challenge

Build a quick multiply function.

Steps:

  • Create a lambda function called multiply
  • It should take two numbers
  • Return the answer
  • Print the result of 4 and 5

Expected output:

text
20

Real World Use Case

Programs use lambda functions for sorting, quick calculations, filtering data, and short helper tasks.

Quiz

  1. What is a lambda function?
  2. How many lines is it usually?
  3. When should you use lambda?
  4. Which keyword creates a lambda function?

Assignment

Create a lambda function called minus that subtracts two numbers and prints the result.

Summary

You learned that lambda functions are short one-line functions used for simple tasks and quick actions.