Master Python Anonymous Functions: Lambda, Map, Filter, Reduce Explained
This article provides a comprehensive guide to Python anonymous (lambda) functions, covering their syntax, execution order, recursion, and practical uses with map, filter, and reduce, while also explaining variable scopes, returning functions, and common pitfalls.
Anonymous Functions
Preface
In the previous article we covered basic function definitions and usage in Python. This article dives deeper into function execution order, decorators, and especially anonymous (lambda) functions.
Function definition recap
def function_name(parameters):
# function body
return resultFunction call:
# Functions execute only when called
function_name()Local and global variables
Different functions have separate scopes. Use global to modify a global variable, or globals()['var']. Nested functions can access the outer variable with nonlocal.
def test1():
name = 'XXX'
print(name)
def test2():
name = 'YYY'
print(name)
test1()
test2() def outer():
name = 'XXX'
def inner():
nonlocal name
print(name)
inner()
outer()Returning a function
def test1():
print("in the test1")
def test2():
print("in the test2")
return test1
test2()()Recursion
Recursion calls a function from within itself and must have a base case to avoid stack overflow.
Self‑calling
Requires a clear termination condition
Problem size reduces each call
Not the most efficient but often convenient
Classic Fibonacci example:
# Fibonacci sequence: 1,1,2,3,5,8,...
def fibonacci(n):
if n <= 2:
return 1
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(6))Adjust recursion limit:
import sys
print(sys.getrecursionlimit())
sys.setrecursionlimit(999999999)
print(sys.getrecursionlimit())Lambda (anonymous) functions
Create with lambda parameters: expression Only a single expression; the result of the expression is returned
Example:
lambda num1, num2: num1 + num2
func = lambda num1, num2: num1 + num2
print(func(1, 2))Using lambda with map, filter, reduce
map applies a function to each element of an iterable and returns a map object.
li = [1,5,3,2,3]
res = map(lambda x: x+1, li)
print(list(res))filter keeps elements where the function returns True.
people = ['sb_laowang','sb_xiaozhang','sb_laozhang','xiaoliu']
res = filter(lambda x: x.startswith('sb'), people)
print(list(res))reduce aggregates a sequence using a binary function.
from functools import reduce
num_li = [1,2,3,4,5,6,7,8,9,10]
res_num = reduce(lambda x, y: x + y, num_li)
print(res_num)Advantages of anonymous functions
Simplify code
Avoid name collisions
When two functions share the same name, the later definition overwrites the earlier one, which can cause bugs. Anonymous functions have no name, eliminating this risk.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
