Functions · Lesson 24 of 39
Scope, Lambda and Recursion
Three ideas complete your picture of functions: scope decides which variables a function can see, lambda lets you write tiny throw-away functions, and recursion lets a function solve a problem by calling itself on a smaller version of it.
In this lesson
- Local and global variables and the LEGB rule
globalandnonlocal- Lambda functions with
sorted,mapandfilter - Recursion: base case, call stack and limits
Scope: where a name is visible
Variables created inside a function are local: they exist only while the function runs and are invisible outside it.
rate = 0.18 # global
def with_tax(amount):
tax = amount * rate # tax is local; rate is read from global
return amount + tax
print(with_tax(100))
try:
print(tax)
except NameError as error:
print("NameError:", error)
118.0 NameError: name 'tax' is not defined
The LEGB rule
When Python meets a name, it searches four places in order and uses the first match:
Name lookup order
- L – Localinside the current function
- E – Enclosinginside any outer function (for nested functions)
- G – Globalat the top level of the module (file)
- B – Built-inPython's own names: print, len, sum…
x = "global"
def outer():
x = "enclosing"
def inner():
x = "local"
print(x)
inner()
print(x)
outer()
print(x)
local enclosing global
global and nonlocal
Reading an outer variable is fine. Assigning to it inside a function creates a new local instead – unless you declare otherwise:
count = 0
def increment():
global count # assign to the module-level name
count += 1
increment()
increment()
print(count)
def make_counter():
total = 0
def step():
nonlocal total # assign to the enclosing function's name
total += 1
return total
return step
counter = make_counter()
print(counter(), counter(), counter())
2 1 2 3
Common mistake: UnboundLocalError
Writing count += 1 inside a function without global count raises UnboundLocalError: cannot access local variable 'count', because the assignment makes count local for the whole function. Better than global: pass the value in and return the new value.
The make_counter example is a closure: the inner function remembers total even after make_counter has returned. Closures are the foundation of decorators (chapter 13).
Lambda: tiny anonymous functions
lambda parameters: expression creates a small function without a name. It can contain only a single expression, whose value is returned automatically.
square = lambda n: n * n # same as def square(n): return n * n
print(square(7))
products = [("pen", 20), ("bag", 650), ("book", 180)]
print(sorted(products, key=lambda p: p[1]))
print(max(products, key=lambda p: p[1])[0])
49
[('pen', 20), ('book', 180), ('bag', 650)]
bagLambdas are best used inline, as the key for sorting or as a quick argument. If you are giving it a name (as with square above), a normal def is clearer – PEP 8 recommends that.
map() and filter()
prices = [100, 250, 80, 400]
with_gst = list(map(lambda p: round(p * 1.18), prices))
cheap = list(filter(lambda p: p < 200, prices))
print(with_gst)
print(cheap)
# The same with comprehensions – usually preferred in Python
print([round(p * 1.18) for p in prices])
print([p for p in prices if p < 200])
[118, 295, 94, 472] [100, 80] [118, 295, 94, 472] [100, 80]
Recursion
A recursive function calls itself. Every recursive solution needs two parts:
- a base case – a simple input answered directly, which stops the recursion;
- a recursive case – which calls the function on a smaller input.
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1) # recursive case
print(factorial(5))
120
The call stack for factorial(4)
- factorial(4)waits for 4 × factorial(3)
- factorial(3)waits for 3 × factorial(2)
- factorial(2)waits for 2 × factorial(1)
- factorial(1) → 1base case: no more calls
- Unwinding2 × 1 = 2 → 3 × 2 = 6 → 4 × 6 = 24
Recursion fits naturally whenever data contains smaller copies of itself – folders inside folders, comments with replies, tree structures:
menu = {
"File": {"New": {}, "Open": {"Recent": {}}},
"Edit": {"Undo": {}},
}
def show(tree, depth=0):
for name, children in tree.items():
print(" " * depth + "- " + name)
show(children, depth + 1)
show(menu)
- File
- New
- Open
- Recent
- Edit
- UndoCommon mistake: no base case
Without a base case (or with one that is never reached), the function calls itself until Python stops it with RecursionError: maximum recursion depth exceeded. The default limit is about 1,000 calls. For deep problems, a loop is usually the better tool in Python.
Recursion that repeats work
The naive Fibonacci function calls itself twice per step and recomputes the same values again and again. Caching the results with functools.lru_cache makes it instant:
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print([fib(i) for i in range(10)])
print(fib(80))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34] 23416728348467685
The @lru_cache line is a decorator – you will write your own in chapter 13.
Practice
Try it yourself
Write a recursive
sum_digits(n):sum_digits(4096)→ 19.Show solution
def sum_digits(n): if n < 10: return n return n % 10 + sum_digits(n // 10) print(sum_digits(4096))19
Sort these names by their last letter using a lambda:
["Arun", "Bela", "Chirag", "Divy"].Show solution
names = ["Arun", "Bela", "Chirag", "Divy"] print(sorted(names, key=lambda n: n[-1]))['Bela', 'Chirag', 'Arun', 'Divy']
Flatten
[1, [2, [3, 4]], 5]into[1, 2, 3, 4, 5]with recursion.Show solution
def flatten(items): result = [] for item in items: if isinstance(item, list): result.extend(flatten(item)) else: result.append(item) return result print(flatten([1, [2, [3, 4]], 5]))[1, 2, 3, 4, 5]
Quick check
What does LEGB stand for?
Local, Enclosing, Global, Built-in – the order Python searches for a name.
Can a lambda contain several statements?
No, only a single expression. Use def for anything more.
What two parts does every recursive function need?
A base case that stops the recursion and a recursive case that moves towards it.
Summary
- Names are looked up Local → Enclosing → Global → Built-in.
global/nonlocalallow assignment to outer names; prefer returning values.lambdais for short inline functions like sort keys.- Recursion needs a base case; cache repeated work with
lru_cache.
Interview practice: Python control flow, functions and scope and decorators, closures and functional Python.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.