Skip to main content

Command Palette

Search for a command to run...

Python Basics — Day 18 Lambda Functions in Python

Published
2 min read
S

Aspiring Full-Stack Developer | Python · Django · React · SQL | documenting my learning journey

Building skills in Python and full-stack development, with a focus on web apps and system design

Junior developer in training — Python, Django, React — preparing for a career in full-stack engineering

From Python basics to full-stack projects, sharing my progress as I grow into a developer

Future full-stack engineer | Learning in public: Python, APIs, Databases, and Web Development

01. What is a Lambda Function?

  • A one-line anonymous function (no name).

  • Defined using the syntax:
    lambda parameters: expression

add = lambda x, y: x + y
print(add(3, 5))   # 8

02. Regular Function vs Lambda Function

# Regular function
def square(x):
    return x * x

# Lambda function
square2 = lambda x: x * x

print(square(4))   # 16
print(square2(4))  # 16

👉 Both give the same result, but lambdas are useful for short, inline code.


03. Common Uses of Lambda Functions

List Sorting with key

nums = [3, 1, 5, 2, 4]
nums.sort(key=lambda x: -x)   # Sort in descending order
print(nums)  # [5, 4, 3, 2, 1]

map() – Apply Function to All Elements

numbers = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, numbers))
print(squares)  # [1, 4, 9, 16]

filter() – Select Elements That Meet a Condition

numbers = [10, 15, 20, 25]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even)  # [10, 20]

reduce() – Accumulate Values

from functools import reduce

numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)  # 24

04. Lambda with Conditional Expression

max_num = lambda a, b: a if a > b else b
print(max_num(10, 20))  # 20

05. Practice Examples

Example 1: Sort Strings by Length

words = ["apple", "banana", "kiwi"]
words.sort(key=lambda w: len(w))
print(words)   # ['kiwi', 'apple', 'banana']

Example 2: Filter Odd Numbers

nums = [1, 2, 3, 4, 5]
odds = list(filter(lambda n: n % 2 == 1, nums))
print(odds)   # [1, 3, 5]

Python Basics

Part 18 of 21

A collection of study notes from my university and self-learning journey. This series covers Python fundamentals step by step — from setup to core concepts — to help both myself and others build a solid foundation in coding.

Up next

Python Basics — Day 19 Modules & Packages (import, from, __main__)

Starting from this post , I’ve changed the format form explaining concepts to presenting problems and solving them. Personally, I’ve found that I learn best when I face a problem and work through the process of fixing it. Learning Goal Learn how to s...

More from this blog

S

Sabin’s DevLog

21 posts

I plan to upload everything I study and prepare here. I hope it can be helpful to others, and I also want my future self to see the learning journey I’ve been through.