In this lesson, you learned how Python Lambda Functions provide a concise way to create small anonymous functions using the lambda keyword. Unlike normal functions created with the def keyword, lambda functions consist of a single expression and automatically return the result without requiring a return statement.
You explored the syntax of lambda functions, learned how to create lambda functions with one or multiple arguments, and understood the differences between lambda functions and normal functions. You also discovered how lambda functions work seamlessly with Python’s built-in functions such as map(), filter(), sorted(), and reduce(), making them ideal for data processing and transformation tasks.
Through practical examples such as square calculators, sorting student records, filtering even numbers, shopping discount calculations, temperature conversion, and sales analysis, you learned how lambda functions simplify code while improving readability and efficiency.
Although lambda functions are powerful, they should be used only for simple expressions. For complex logic involving multiple statements, loops, or extensive conditional processing, normal functions created with the def keyword remain the better choice.
lambda keyword.map(), filter(), sorted(), and reduce().A lambda function is a small anonymous function created using the lambda keyword that contains a single expression.
They are called anonymous because they are created without using the def keyword to define a named function.
No. A lambda function can contain only one expression.
return keyword?No. The result of the expression is returned automatically.
Lambda functions are best for short, simple operations, especially when used with functions such as map(), filter(), and sorted().
Yes. Lambda functions can accept any number of arguments but contain only one expression.
A normal function uses the def keyword and can contain multiple statements, while a lambda function uses the lambda keyword and contains only one expression.
reduce() a built-in function?No. In Python 3, reduce() is available in the functools module and must be imported before use.
map() with a lambda function to calculate the cubes of numbers in a list.filter() with a lambda function to extract numbers greater than 50.sorted() and a lambda function.reduce() and a lambda function to calculate the product of numbers in a list.map() used with lambda functions?filter() used with lambda functions?reduce() imported from the functools module?Create a Python program that analyzes student marks using lambda functions.
Your program should:
sorted() and a lambda function.filter().map().reduce().Students Sorted by Marks
Amit : 72
Rahul : 84
Neha : 91
Students with Marks >= 75
Rahul : 84
Neha : 91
Marks After Grace
Amit : 77
Rahul : 89
Neha : 96
Total Marks : 247
Congratulations! You have successfully learned Python Lambda Functions. You now understand how to create anonymous functions, work with lambda expressions, and combine them with map(), filter(), sorted(), and reduce() to write concise and efficient Python programs.
In the next lesson, you will explore Python Recursion: Complete Guide for Beginners. You will learn what recursion is, how recursive functions work, the importance of the base case, recursive call flow, recursion versus loops, common mistakes, optimization techniques, and practical examples such as factorial calculation, Fibonacci series generation, and tree traversal.
In the previous section, you learned the basic concepts of recursion, including recursive functions, the base case, the recursive case, and the call stack. In this section, you will apply these concepts to solve common programming problems such as calculating factorials, generating Fibonacci numbers, finding the sum of natural numbers, processing strings and lists recursively, and understanding recursion depth.
The factorial of a positive integer n is calculated as:
n! = n × (n - 1) × (n - 2) × ... × 1
For example:
5! = 5 × 4 × 3 × 2 × 1 = 120
def factorial(number):
if number == 0 or number == 1:
return 1
return number * factorial(number - 1)
print(factorial(5))
Output
120
The function repeatedly calls itself until it reaches the base case.
factorial(5)
↓
5 × factorial(4)
↓
5 × 4 × factorial(3)
↓
5 × 4 × 3 × factorial(2)
↓
5 × 4 × 3 × 2 × factorial(1)
↓
5 × 4 × 3 × 2 × 1
↓
120
In the Fibonacci sequence, every number is the sum of the previous two numbers.
0 1 1 2 3 5 8 13 ...
def fibonacci(number):
if number <= 1:
return number
return fibonacci(number - 1) + fibonacci(number - 2)
for i in range(8):
print(fibonacci(i), end=" ")
Output
0 1 1 2 3 5 8 13
This example demonstrates how one recursive function can call itself multiple times.
Recursion can also calculate the sum of natural numbers.
def total(number):
if number == 1:
return 1
return number + total(number - 1)
print(total(5))
Output
15
The calculation performed is:
5 + 4 + 3 + 2 + 1 = 15
Recursion can process strings character by character.
def print_characters(text):
if text == "":
return
print(text[0])
print_characters(text[1:])
print_characters("Python")
Output
P
y
t
h
o
n
Each recursive call processes one character and passes the remaining string.
Lists can also be processed recursively.
def print_list(items):
if len(items) == 0:
return
print(items[0])
print_list(items[1:])
numbers = [10, 20, 30, 40]
print_list(numbers)
Output
10
20
30
40
The function prints one element and recursively processes the remaining list.
Every recursive function call creates a new stack frame.
Python limits the number of recursive calls to prevent programs from consuming excessive memory.
If recursion exceeds this limit, Python raises a RecursionError.
def endless(number):
print(number)
endless(number + 1)
endless(1)
Output
RecursionError: maximum recursion depth exceeded
This occurs because no base case stops the recursion.
Consider the following recursive function.
def show(number):
if number == 0:
return
print(number)
show(number - 1)
show(3)
The call stack grows as follows:
show(3)
↓
show(2)
↓
show(1)
↓
show(0)
↓
Return
↓
Return
↓
Return
Python removes stack frames in reverse order after reaching the base case.
| Recursion | Loops |
|---|---|
| Uses function calls. | Uses for or while loops. |
| Requires a base case. | Requires a loop condition. |
| Uses additional memory for the call stack. | Consumes less memory. |
| Often easier for recursive problems. | Often faster for repetitive tasks. |
Can cause RecursionError. |
Can cause infinite loops if conditions are incorrect. |
Consider the following program.
def total(number):
if number == 1:
return 1
return number + total(number - 1)
print(total(4))
Execution Steps
4.4 + total(3).3 + total(2).2 + total(1).1.Output
10
Without a base case, recursion continues indefinitely.
The recursive call should always move closer to the stopping condition.
Deep recursion can exceed Python's recursion limit.
Each recursive call creates a new stack frame, unlike loops.
Not every programming problem requires recursion. In many cases, loops provide a simpler and more efficient solution.
In this section, you learned how recursion is applied to practical programming problems such as factorial calculation, Fibonacci series generation, finding the sum of natural numbers, processing strings and lists recursively, and understanding recursion depth. You also visualized the call stack, compared recursion with loops in greater detail, followed the execution flow of recursive programs, and reviewed common beginner mistakes. In the next section, you will solve more advanced recursive problems, including power calculation, string reversal, palindrome checking, recursive binary search, greatest common divisor (GCD), introductory tree traversal, and directory traversal examples.
Recursion is used extensively in software development to solve problems that can be divided into smaller versions of the same problem. Common applications include mathematical calculations, searching algorithms, tree traversal, file system navigation, and string processing.
In this section, you will explore practical recursive programs that demonstrate how recursion is applied to real-world programming tasks. Each example emphasizes the importance of a proper base case and recursive call.
This recursive function calculates the power of a number.
def power(base, exponent):
if exponent == 0:
return 1
return base * power(base, exponent - 1)
print(power(2, 5))
Output
32
The function repeatedly multiplies the base until the exponent reaches zero.
Recursion can reverse a string by processing one character at a time.
def reverse(text):
if len(text) == 0:
return ""
return reverse(text[1:]) + text[0]
print(reverse("Python"))
Output
nohtyP
Each recursive call removes the first character and appends it after the remaining reversed string.
A palindrome is a word that reads the same forwards and backwards.
def palindrome(text):
if len(text) <= 1:
return True
if text[0] != text[-1]:
return False
return palindrome(text[1:-1])
print(palindrome("madam"))
print(palindrome("python"))
Output
True
False
The function compares the first and last characters, then recursively checks the remaining substring.
Binary search efficiently searches a sorted list by repeatedly dividing it into halves.
def binary_search(numbers, target, left, right):
if left > right:
return -1
middle = (left + right) // 2
if numbers[middle] == target:
return middle
elif target < numbers[middle]:
return binary_search(numbers, target, left, middle - 1)
else:
return binary_search(numbers, target, middle + 1, right)
values = [5, 10, 15, 20, 25, 30]
print(binary_search(values, 20, 0, len(values) - 1))
Output
3
The function repeatedly searches the appropriate half of the list until the target is found.
The Euclidean algorithm is a classic example of recursion.
def gcd(a, b):
if b == 0:
return a
return gcd(b, a % b)
print(gcd(48, 18))
Output
6
The recursive calls continue until the second number becomes zero.
Recursion is commonly used to traverse tree structures because each node can contain smaller subtrees.
tree = {
"A": ["B", "C"],
"B": ["D", "E"],
"C": [],
"D": [],
"E": []
}
def traverse(node):
print(node)
for child in tree[node]:
traverse(child)
traverse("A")
Output
A
B
D
E
C
The recursive function visits every child node until all branches are explored.
Recursion is often used to explore folders and subfolders.
Root Folder
├── Documents
│ ├── Notes
│ └── Reports
├── Images
└── Videos
A recursive function visits every folder and then recursively explores its subfolders until no folders remain.
This recursive function counts the number of digits in an integer.
def count_digits(number):
if number < 10:
return 1
return 1 + count_digits(number // 10)
print(count_digits(987654))
Output
6
Each recursive call removes one digit until only a single digit remains.
def maximum(numbers):
if len(numbers) == 1:
return numbers[0]
largest = maximum(numbers[1:])
if numbers[0] > largest:
return numbers[0]
return largest
print(maximum([12, 45, 9, 81, 33]))
Output
81
Consider the following recursive program.
def power(base, exponent):
if exponent == 0:
return 1
return base * power(base, exponent - 1)
print(power(3, 3))
Execution Steps
base = 3 and exponent = 3.3 × power(3, 2).3 × power(3, 1).3 × power(3, 0).1.Output
27
Every recursive function must include a condition that stops further recursive calls.
Each recursive call should reduce the problem size.
Write recursive functions that solve one well-defined task.
Very deep recursion can exceed Python's recursion limit and reduce performance.
Use recursion for naturally recursive problems such as trees, directories, and divide-and-conquer algorithms. For simple repetitive tasks, loops are often more efficient.
In this section, you explored practical applications of recursion, including power calculation, string reversal, palindrome checking, recursive binary search, the Euclidean algorithm for finding the greatest common divisor, tree traversal, directory traversal concepts, counting digits, and finding the maximum value in a list. You also learned best practices for designing recursive functions, reviewed common beginner mistakes, and followed the execution flow of recursive programs. In the final section, you will review the complete lesson through a lesson summary, key takeaways, frequently asked questions, coding exercises, interview questions, a mini project, and a preview of the next lesson on Python Modules & Packages.