Python Basics — Day 18 Lambda Functions in Python
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]