Functions & Scope
Lambda
Anonymous Functions
You need to sort users by age. Writing a separate get_age() function feels
like overkill for one use. Lambda lets you define small functions inline:
sorted(users, key=lambda u: u.age).
Basic lambda syntax
Create a small anonymous function.
def main():
print("=== Basic Lambda ===\n")
# Regular function
def square(x):
return x * x
# Lambda equivalent
square_lambda = lambda x: x * x
# Both work the same!
print(f"square(5) = {square(5)}")
print(f"square_lambda(5) = {square_lambda(5)}")
print("\n=== Lambda Syntax ===")
# lambda arguments: expression
add = lambda a, b: a + b
multiply = lambda a, b: a * b
print(f"add(3, 4) = {add(3, 4)}")
print(f"multiply(3, 4) = {multiply(3, 4)}")
print("\n=== Inline Usage (Most Common) ===")
numbers = [1, 2, 3, 4, 5]
# Lambda used directly, not assigned
squared = list(map(lambda x: x ** 2, numbers))
print(f"Squares of {numbers}: {squared}")
print("\n=== Type Comparison ===")
print(f"type(square): {type(square)}")
print(f"type(square_lambda): {type(square_lambda)}")
print(f"square.__name__: '{square.__name__}'")
print(f"square_lambda.__name__: '{square_lambda.__name__}'") # <lambda>
if __name__ == "__main__":
main()
square_lambda ← <function main.<locals>.<lambda> at ⟨addr A⟩>
1#@var=default,compare2def main():3 print("=== Basic Lambda ===\n")4 5 # Regular function #?regular6 def square(x):7 return x * x8 9 # Lambda equivalent #?lambda10 square_lambda→ <function main.<locals>.<lambda> at ⟨addr A⟩> = lambda x: x * x11 12 # Both work the same!13 print(f"square(5) = {square(5)}")14 print(f"square_lambda(5) = {square_lambda(5)}")output=== Basic Lambda ===def square(x):
5# Regular function #?regular6def square(x5):7 return x5 * xadd ← <function main.<locals>.<lambda> at ⟨addr B⟩>, multiply ← <function main.<locals>.<lambda> at ⟨addr C⟩>
12# Both work the same!13print(f"square(5) = {square(5)}")14print(f"square_lambda(5) = {square_lambda(5)}")1516print("\n=== Lambda Syntax ===") #?syntax17# lambda arguments: expression18add→ <function main.<locals>.<lambda> at ⟨addr B⟩> = lambda a, b: a + b19multiply→ <function main.<locals>.<lambda> at ⟨addr C⟩> = lambda a, b: a * b2021print(f"add(3, 4) = {add(3, 4)}")22print(f"multiply(3, 4) = {multiply(3, 4)}")2324print("\n=== Inline Usage (Most Common) ===") #?inline25numbers→ [1, 2, 3, 4, 5] = [1, 2, 3, 4, 5]2627# Lambda used directly, not assigned28squared→ [1, 4, 9, 16, 25] = list(map(lambda x: x ** 2, numbers[1, 2, 3, 4, 5]))29print(f"Squares of {numbers[1, 2, 3, 4, 5]}: {squared[1, 4, 9, 16, 25]}")3031#@var=_,!32print("\n=== Type Comparison ===")33print(f"type(square): {type(square<function main.<locals>.square at ⟨addr D⟩>)}")34print(f"type(square_lambda): {type(square_lambda<function main.<locals>.<lambda> at ⟨addr A⟩>)}")35print(f"square.__name__: '{square.__name__square}'")36print(f"square_lambda.__name__: '{square_lambda.__name__<lambda>}'") # <lambda>37#@var=_,!outputsquare(5) = 25 square_lambda(5) = 25 === Lambda Syntax === add(3, 4) = 7 multiply(3, 4) = 12 === Inline Usage (Most Common) === Squares of [1, 2, 3, 4, 5]: [1, 4, 9, 16, 25] === Type Comparison === type(square): <class 'function'> type(square_lambda): <class 'function'> square.__name__: 'square' square_lambda.__name__: '<lambda>'main()
39if __name__ == "__main__":40 main()41#@help regular
lambda x: x * 2 is equivalent to def f(x): return x * 2.
Lambda as sort key
Use lambda to customize sorting.
def main():
print("=== Lambda as Sort Key ===\n")
# Sort strings by length
words = ["apple", "pie", "banana", "kiwi"]
print(f"Original: {words}")
sorted_by_length = sorted(words, key=lambda w: len(w))
print(f"By length: {sorted_by_length}")
print("\n=== Sort Objects by Attribute ===")
people = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 35}
]
# Sort by age
by_age = sorted(people, key=lambda p: p["age"])
print("By age:")
for person in by_age:
print(f" {person['name']}: {person['age']}")
# Sort by name
by_name = sorted(people, key=lambda p: p["name"])
print("\nBy name:")
for person in by_name:
print(f" {person['name']}: {person['age']}")
print("\n=== Reverse Sort ===")
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
descending = sorted(numbers, key=lambda x: -x)
print(f"Descending: {descending}")
# Or use reverse=True
descending2 = sorted(numbers, reverse=True)
print(f"With reverse=True: {descending2}")
print("\n=== Complex Sort Key ===")
students = [
("Alice", 85, 22),
("Bob", 90, 20),
("Charlie", 85, 21)
]
# Sort by grade (desc), then age (asc)
sorted_students = sorted(students, key=lambda s: (-s[1], s[2]))
print("By grade (desc), then age (asc):")
for name, grade, age in sorted_students:
print(f" {name}: grade={grade}, age={age}")
if __name__ == "__main__":
main()
words ← ['apple', 'pie', 'banana', 'kiwi'], sorted_by_length ← ['pie', 'kiwi', 'apple', 'banana']
1#@var=default,complex2def main():3 print("=== Lambda as Sort Key ===\n")4 5 # Sort strings by length #?bylen6 words→ ['apple', 'pie', 'banana', 'kiwi'] = ["apple", "pie", "banana", "kiwi"]7 print(f"Original: {words['apple', 'pie', 'banana', 'kiwi']}")8 9 sorted_by_length→ ['pie', 'kiwi', 'apple', 'banana'] = sorted(words['apple', 'pie', 'banana', 'kiwi'], key=lambda w: len(w))10 print(f"By length: {sorted_by_length['pie', 'kiwi', 'apple', 'banana']}")11 12 print("\n=== Sort Objects by Attribute ===") #?objects13 people→ [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 35}] = [14 {"name": "Alice", "age": 30},15 {"name": "Bob", "age": 25},16 {"name": "Charlie", "age": 35}17 ]18 19 # Sort by age20 by_age→ [{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Charlie', 'age': 35}] = sorted(people[{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 35}], key=lambda p: p["age"])21 print("By age:")22 for person in by_age:output=== Lambda as Sort Key === Original: ['apple', 'pie', 'banana', 'kiwi'] By length: ['pie', 'kiwi', 'apple', 'banana'] === Sort Objects by Attribute === By age:for person in by_age:
pass 1 of 321print("By age:")22for person{'name': 'Bob', 'age': 25} in by_age[{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Charlie', 'age': 35}]:23 print(f" {person['name']Bob}: {person['age']25}")output Bob: 25All 3 passes — pass 1 is the card above pass personperson[’name’]person[’age’]1 {'name': 'Bob', 'age': 25} Bob 25 2 {'name': 'Alice', 'age': 30} Alice 30 3 {'name': 'Charlie', 'age': 35} Charlie 35 by_name ← [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 35}]
25# Sort by name26by_name→ [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 35}] = sorted(people[{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 35}], key=lambda p: p["name"])27print("\nBy name:")28for person in by_name:output By name:for person in by_name:
pass 1 of 327print("\nBy name:")28for person{'name': 'Alice', 'age': 30} in by_name[{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}, {'name': 'Charlie', 'age': 35}]:29 print(f" {person['name']Alice}: {person['age']30}")output Alice: 30All 3 passes — pass 1 is the card above pass personperson[’name’]person[’age’]1 {'name': 'Alice', 'age': 30} Alice 30 2 {'name': 'Bob', 'age': 25} Bob 25 3 {'name': 'Charlie', 'age': 35} Charlie 35 numbers ← [3, 1, 4, 1, 5, 9, 2, 6], descending ← [9, 6, 5, 4, 3, 2, 1, 1]
31print("\n=== Reverse Sort ===") #?reverse32numbers→ [3, 1, 4, 1, 5, 9, 2, 6] = [3, 1, 4, 1, 5, 9, 2, 6]33descending→ [9, 6, 5, 4, 3, 2, 1, 1] = sorted(numbers[3, 1, 4, 1, 5, 9, 2, 6], key=lambda x: -x)34print(f"Descending: {descending[9, 6, 5, 4, 3, 2, 1, 1]}")3536# Or use reverse=True37descending2→ [9, 6, 5, 4, 3, 2, 1, 1] = sorted(numbers[3, 1, 4, 1, 5, 9, 2, 6], reverse=True)38print(f"With reverse=True: {descending2[9, 6, 5, 4, 3, 2, 1, 1]}")3940#@var=_,!41print("\n=== Complex Sort Key ===")42students→ [('Alice', 85, 22), ('Bob', 90, 20), ('Charlie', 85, 21)] = [43 ("Alice", 85, 22),44 ("Bob", 90, 20),45 ("Charlie", 85, 21)46]47# Sort by grade (desc), then age (asc) #?complex48sorted_students→ [('Bob', 90, 20), ('Charlie', 85, 21), ('Alice', 85, 22)] = sorted(students[('Alice', 85, 22), ('Bob', 90, 20), ('Charlie', 85, 21)], key=lambda s: (-s[1], s[2]))49print("By grade (desc), then age (asc):")50for name, grade, age in sorted_students:output === Reverse Sort === Descending: [9, 6, 5, 4, 3, 2, 1, 1] With reverse=True: [9, 6, 5, 4, 3, 2, 1, 1] === Complex Sort Key === By grade (desc), then age (asc):for name, grade, age in sorted_students:
pass 1 of 349print("By grade (desc), then age (asc):")50for nameBob, grade90, age20 in sorted_students[('Bob', 90, 20), ('Charlie', 85, 21), ('Alice', 85, 22)]:51 print(f" {nameBob}: grade={grade90}, age={age20}")52#@var=_,!output Bob: grade=90, age=20All 3 passes — pass 1 is the card above pass namegradeage1 Bob 90 20 2 Charlie 85 21 3 Alice 85 22 main()
54if __name__ == "__main__":55 main()56#@help bylen
sorted(items, key=lambda x: x.attr) sorts by any attribute or computation.
See the Sort Key
sorted does not compare the whole object when a key is supplied. It first asks the key function for a simpler comparison value.
Lambda with filter and map
Transform and filter collections inline.
def main():
print("=== Lambda with filter() ===\n")
numbers = [1, -2, 3, -4, 5, -6, 7, -8, 9, -10]
print(f"Numbers: {numbers}")
# Filter positive numbers
positives = list(filter(lambda x: x > 0, numbers))
print(f"Positives: {positives}")
# Filter even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Evens: {evens}")
print("\n=== Lambda with map() ===")
# Square each number
squared = list(map(lambda x: x ** 2, numbers))
print(f"Squared: {squared}")
# Absolute value
absolutes = list(map(lambda x: abs(x), numbers))
print(f"Absolutes: {absolutes}")
print("\n=== Combining filter and map ===")
# Square of positive numbers only
result = list(map(lambda x: x ** 2,
filter(lambda x: x > 0, numbers)))
print(f"Squares of positives: {result}")
print("\n=== List Comprehension Alternative ===")
# Often clearer than map/filter!
positives_comp = [x for x in numbers if x > 0]
print(f"Positives (comprehension): {positives_comp}")
squared_comp = [x ** 2 for x in numbers]
print(f"Squared (comprehension): {squared_comp}")
combined_comp = [x ** 2 for x in numbers if x > 0]
print(f"Squares of positives (comprehension): {combined_comp}")
if __name__ == "__main__":
main()
def main():
print("=== Lambda with filter() ===\n")
numbers = [2, 4, 6, 8]
print(f"Numbers: {numbers}")
# Filter positive numbers
positives = list(filter(lambda x: x > 0, numbers))
print(f"Positives: {positives}")
# Filter even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Evens: {evens}")
print("\n=== Lambda with map() ===")
# Square each number
squared = list(map(lambda x: x ** 2, numbers))
print(f"Squared: {squared}")
# Absolute value
absolutes = list(map(lambda x: abs(x), numbers))
print(f"Absolutes: {absolutes}")
print("\n=== Combining filter and map ===")
# Square of positive numbers only
result = list(map(lambda x: x ** 2,
filter(lambda x: x > 0, numbers)))
print(f"Squares of positives: {result}")
print("\n=== List Comprehension Alternative ===")
# Often clearer than map/filter!
positives_comp = [x for x in numbers if x > 0]
print(f"Positives (comprehension): {positives_comp}")
squared_comp = [x ** 2 for x in numbers]
print(f"Squared (comprehension): {squared_comp}")
combined_comp = [x ** 2 for x in numbers if x > 0]
print(f"Squares of positives (comprehension): {combined_comp}")
if __name__ == "__main__":
main()
def main():
print("=== Lambda with filter() ===\n")
numbers = [-3, -1, 0, 1, 3]
print(f"Numbers: {numbers}")
# Filter positive numbers
positives = list(filter(lambda x: x > 0, numbers))
print(f"Positives: {positives}")
# Filter even numbers
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(f"Evens: {evens}")
print("\n=== Lambda with map() ===")
# Square each number
squared = list(map(lambda x: x ** 2, numbers))
print(f"Squared: {squared}")
# Absolute value
absolutes = list(map(lambda x: abs(x), numbers))
print(f"Absolutes: {absolutes}")
print("\n=== Combining filter and map ===")
# Square of positive numbers only
result = list(map(lambda x: x ** 2,
filter(lambda x: x > 0, numbers)))
print(f"Squares of positives: {result}")
print("\n=== List Comprehension Alternative ===")
# Often clearer than map/filter!
positives_comp = [x for x in numbers if x > 0]
print(f"Positives (comprehension): {positives_comp}")
squared_comp = [x ** 2 for x in numbers]
print(f"Squared (comprehension): {squared_comp}")
combined_comp = [x ** 2 for x in numbers if x > 0]
print(f"Squares of positives (comprehension): {combined_comp}")
if __name__ == "__main__":
main()
numbers ← [1, -2, 3, -4, 5, -6, 7, -8, 9, -10], positives ← [1, 3, 5, 7, 9]
1#@var=default,comprehension2def main():3 print("=== Lambda with filter() ===\n")4 5 numbers→ [1, -2, 3, -4, 5, -6, 7, -8, 9, -10] = [1, -2, 3, -4, 5, -6, 7, -8, 9, -10] #@numbers=[2, 4, 6, 8], [-3, -1, 0, 1, 3]6 print(f"Numbers: {numbers[1, -2, 3, -4, 5, -6, 7, -8, 9, -10]}")7 8 # Filter positive numbers #?filter9 positives→ [1, 3, 5, 7, 9] = list(filter(lambda x: x > 0, numbers[1, -2, 3, -4, 5, -6, 7, -8, 9, -10]))10 print(f"Positives: {positives[1, 3, 5, 7, 9]}")11 12 # Filter even numbers13 evens→ [-2, -4, -6, -8, -10] = list(filter(lambda x: x % 2 == 0, numbers[1, -2, 3, -4, 5, -6, 7, -8, 9, -10]))14 print(f"Evens: {evens[-2, -4, -6, -8, -10]}")15 16 print("\n=== Lambda with map() ===") #?map17 18 # Square each number19 squared→ [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] = list(map(lambda x: x ** 2, numbers[1, -2, 3, -4, 5, -6, 7, -8, 9, -10]))20 print(f"Squared: {squared[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]}")21 22 # Absolute value23 absolutes→ [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] = list(map(lambda x: abs(x), numbers[1, -2, 3, -4, 5, -6, 7, -8, 9, -10]))24 print(f"Absolutes: {absolutes[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}")25 26 print("\n=== Combining filter and map ===") #?combine27 28 # Square of positive numbers only29 result→ [1, 9, 25, 49, 81] = list(map(lambda x: x ** 2, 30 filter(lambda x: x > 0, numbers[1, -2, 3, -4, 5, -6, 7, -8, 9, -10])))31 print(f"Squares of positives: {result[1, 9, 25, 49, 81]}")32 33 #@var=_,!34 print("\n=== List Comprehension Alternative ===")35 # Often clearer than map/filter! #?comprehension36 positives_comp→ [1, 3, 5, 7, 9] = [x for x in numbers[1, -2, 3, -4, 5, -6, 7, -8, 9, -10] if x > 0]37 print(f"Positives (comprehension): {positives_comp[1, 3, 5, 7, 9]}")38 39 squared_comp→ [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] = [x ** 2 for x in numbers[1, -2, 3, -4, 5, -6, 7, -8, 9, -10]]40 print(f"Squared (comprehension): {squared_comp[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]}")41 42 combined_comp→ [1, 9, 25, 49, 81] = [x ** 2 for x in numbers[1, -2, 3, -4, 5, -6, 7, -8, 9, -10] if x > 0]43 print(f"Squares of positives (comprehension): {combined_comp[1, 9, 25, 49, 81]}")44 #@var=_,!output=== Lambda with filter() === Numbers: [1, -2, 3, -4, 5, -6, 7, -8, 9, -10] Positives: [1, 3, 5, 7, 9] Evens: [-2, -4, -6, -8, -10] === Lambda with map() === Squared: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] Absolutes: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] === Combining filter and map === Squares of positives: [1, 9, 25, 49, 81] === List Comprehension Alternative === Positives (comprehension): [1, 3, 5, 7, 9] Squared (comprehension): [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] Squares of positives (comprehension): [1, 9, 25, 49, 81]main()
46if __name__ == "__main__":47 main()48#@help filter
numbers ← [2, 4, 6, 8], positives ← [2, 4, 6, 8], evens ← [2, 4, 6, 8]
1def main():2 print("=== Lambda with filter() ===\n")3 4 numbers→ [2, 4, 6, 8] = [2, 4, 6, 8]5 print(f"Numbers: {numbers[2, 4, 6, 8]}")6 7 # Filter positive numbers8 positives→ [2, 4, 6, 8] = list(filter(lambda x: x > 0, numbers[2, 4, 6, 8]))9 print(f"Positives: {positives[2, 4, 6, 8]}")10 11 # Filter even numbers12 evens→ [2, 4, 6, 8] = list(filter(lambda x: x % 2 == 0, numbers[2, 4, 6, 8]))13 print(f"Evens: {evens[2, 4, 6, 8]}")14 15 print("\n=== Lambda with map() ===")16 17 # Square each number18 squared→ [4, 16, 36, 64] = list(map(lambda x: x ** 2, numbers[2, 4, 6, 8]))19 print(f"Squared: {squared[4, 16, 36, 64]}")20 21 # Absolute value22 absolutes→ [2, 4, 6, 8] = list(map(lambda x: abs(x), numbers[2, 4, 6, 8]))23 print(f"Absolutes: {absolutes[2, 4, 6, 8]}")24 25 print("\n=== Combining filter and map ===")26 27 # Square of positive numbers only28 result→ [4, 16, 36, 64] = list(map(lambda x: x ** 2, 29 filter(lambda x: x > 0, numbers[2, 4, 6, 8])))30 print(f"Squares of positives: {result[4, 16, 36, 64]}")31 32 print("\n=== List Comprehension Alternative ===")33 # Often clearer than map/filter!34 positives_comp→ [2, 4, 6, 8] = [x for x in numbers[2, 4, 6, 8] if x > 0]35 print(f"Positives (comprehension): {positives_comp[2, 4, 6, 8]}")36 37 squared_comp→ [4, 16, 36, 64] = [x ** 2 for x in numbers[2, 4, 6, 8]]38 print(f"Squared (comprehension): {squared_comp[4, 16, 36, 64]}")39 40 combined_comp→ [4, 16, 36, 64] = [x ** 2 for x in numbers[2, 4, 6, 8] if x > 0]41 print(f"Squares of positives (comprehension): {combined_comp[4, 16, 36, 64]}")output=== Lambda with filter() === Numbers: [2, 4, 6, 8] Positives: [2, 4, 6, 8] Evens: [2, 4, 6, 8] === Lambda with map() === Squared: [4, 16, 36, 64] Absolutes: [2, 4, 6, 8] === Combining filter and map === Squares of positives: [4, 16, 36, 64] === List Comprehension Alternative === Positives (comprehension): [2, 4, 6, 8] Squared (comprehension): [4, 16, 36, 64] Squares of positives (comprehension): [4, 16, 36, 64]main()
43if __name__ == "__main__":44 main()
numbers ← [-3, -1, 0, 1, 3], positives ← [1, 3], evens ← [0], squared ← [9, 1, 0, 1, 9]
1def main():2 print("=== Lambda with filter() ===\n")3 4 numbers→ [-3, -1, 0, 1, 3] = [-3, -1, 0, 1, 3]5 print(f"Numbers: {numbers[-3, -1, 0, 1, 3]}")6 7 # Filter positive numbers8 positives→ [1, 3] = list(filter(lambda x: x > 0, numbers[-3, -1, 0, 1, 3]))9 print(f"Positives: {positives[1, 3]}")10 11 # Filter even numbers12 evens→ [0] = list(filter(lambda x: x % 2 == 0, numbers[-3, -1, 0, 1, 3]))13 print(f"Evens: {evens[0]}")14 15 print("\n=== Lambda with map() ===")16 17 # Square each number18 squared→ [9, 1, 0, 1, 9] = list(map(lambda x: x ** 2, numbers[-3, -1, 0, 1, 3]))19 print(f"Squared: {squared[9, 1, 0, 1, 9]}")20 21 # Absolute value22 absolutes→ [3, 1, 0, 1, 3] = list(map(lambda x: abs(x), numbers[-3, -1, 0, 1, 3]))23 print(f"Absolutes: {absolutes[3, 1, 0, 1, 3]}")24 25 print("\n=== Combining filter and map ===")26 27 # Square of positive numbers only28 result→ [1, 9] = list(map(lambda x: x ** 2, 29 filter(lambda x: x > 0, numbers[-3, -1, 0, 1, 3])))30 print(f"Squares of positives: {result[1, 9]}")31 32 print("\n=== List Comprehension Alternative ===")33 # Often clearer than map/filter!34 positives_comp→ [1, 3] = [x for x in numbers[-3, -1, 0, 1, 3] if x > 0]35 print(f"Positives (comprehension): {positives_comp[1, 3]}")36 37 squared_comp→ [9, 1, 0, 1, 9] = [x ** 2 for x in numbers[-3, -1, 0, 1, 3]]38 print(f"Squared (comprehension): {squared_comp[9, 1, 0, 1, 9]}")39 40 combined_comp→ [1, 9] = [x ** 2 for x in numbers[-3, -1, 0, 1, 3] if x > 0]41 print(f"Squares of positives (comprehension): {combined_comp[1, 9]}")output=== Lambda with filter() === Numbers: [-3, -1, 0, 1, 3] Positives: [1, 3] Evens: [0] === Lambda with map() === Squared: [9, 1, 0, 1, 9] Absolutes: [3, 1, 0, 1, 3] === Combining filter and map === Squares of positives: [1, 9] === List Comprehension Alternative === Positives (comprehension): [1, 3] Squared (comprehension): [9, 1, 0, 1, 9] Squares of positives (comprehension): [1, 9]main()
43if __name__ == "__main__":44 main()
filter(lambda x: x > 0, nums) keeps positives. map(lambda x: x*2, nums) doubles.
Multiple arguments in lambda
Lambdas can take multiple (or zero) arguments.
def main():
print("=== Lambda with Multiple Arguments ===\n")
# Two arguments
add = lambda x, y: x + y
multiply = lambda x, y: x * y
print(f"add(5, 3) = {add(5, 3)}")
print(f"multiply(5, 3) = {multiply(5, 3)}")
# Three or more
volume = lambda l, w, h: l * w * h
print(f"volume(2, 3, 4) = {volume(2, 3, 4)}")
print("\n=== Lambda with No Arguments ===")
get_pi = lambda: 3.14159
greet = lambda: "Hello, World!"
print(f"get_pi() = {get_pi()}")
print(f"greet() = {greet()}")
print("\n=== Lambda with Default Arguments ===")
power = lambda x, n=2: x ** n
print(f"power(5) = {power(5)}") # 5^2 = 25
print(f"power(5, 3) = {power(5, 3)}") # 5^3 = 125
greet_person = lambda name, greeting="Hello": f"{greeting}, {name}!"
print(greet_person("Alice"))
print(greet_person("Bob", "Hi"))
print("\n=== Practical: reduce() ===")
from functools import reduce
numbers = [1, 2, 3, 4, 5]
# Sum using reduce
total = reduce(lambda acc, x: acc + x, numbers)
print(f"Sum of {numbers} = {total}")
# Product using reduce
product = reduce(lambda acc, x: acc * x, numbers)
print(f"Product of {numbers} = {product}")
# Max using reduce
maximum = reduce(lambda a, b: a if a > b else b, numbers)
print(f"Max of {numbers} = {maximum}")
if __name__ == "__main__":
main()
add ← <function main.<locals>.<lambda> at ⟨addr A⟩>, multiply ← <function main.<locals>.<lambda> at ⟨addr B⟩>
1#@var=default,practical2def main():3 print("=== Lambda with Multiple Arguments ===\n")4 5 # Two arguments #?twoargs6 add→ <function main.<locals>.<lambda> at ⟨addr A⟩> = lambda x, y: x + y7 multiply→ <function main.<locals>.<lambda> at ⟨addr B⟩> = lambda x, y: x * y8 9 print(f"add(5, 3) = {add(5, 3)}")10 print(f"multiply(5, 3) = {multiply(5, 3)}")11 12 # Three or more #?moreargs13 volume→ <function main.<locals>.<lambda> at ⟨addr C⟩> = lambda l, w, h: l * w * h14 print(f"volume(2, 3, 4) = {volume(2, 3, 4)}")15 16 print("\n=== Lambda with No Arguments ===") #?noargs17 18 get_pi→ <function main.<locals>.<lambda> at ⟨addr D⟩> = lambda: 3.1415919 greet→ <function main.<locals>.<lambda> at ⟨addr E⟩> = lambda: "Hello, World!"20 21 print(f"get_pi() = {get_pi()}")22 print(f"greet() = {greet()}")23 24 print("\n=== Lambda with Default Arguments ===") #?defaults25 26 power→ <function main.<locals>.<lambda> at ⟨addr F⟩> = lambda x, n=2: x ** n27 print(f"power(5) = {power(5)}") # 5^2 = 2528 print(f"power(5, 3) = {power(5, 3)}") # 5^3 = 12529 30 greet_person→ <function main.<locals>.<lambda> at ⟨addr G⟩> = lambda name, greeting="Hello": f"{greeting}, {name}!"31 print(greet_person("Alice"))32 print(greet_person("Bob", "Hi"))33 34 #@var=_,!35 print("\n=== Practical: reduce() ===") #?reduce36 from functools import reduce37 38 numbers→ [1, 2, 3, 4, 5] = [1, 2, 3, 4, 5]39 40 # Sum using reduce41 total→ 15 = reduce(lambda acc, x: acc + x, numbers[1, 2, 3, 4, 5])42 print(f"Sum of {numbers[1, 2, 3, 4, 5]} = {total15}")43 44 # Product using reduce45 product→ 120 = reduce(lambda acc, x: acc * x, numbers[1, 2, 3, 4, 5])46 print(f"Product of {numbers[1, 2, 3, 4, 5]} = {product120}")47 48 # Max using reduce49 maximum→ 5 = reduce(lambda a, b: a if a > b else b, numbers[1, 2, 3, 4, 5])50 print(f"Max of {numbers[1, 2, 3, 4, 5]} = {maximum5}")51 #@var=_,!output=== Lambda with Multiple Arguments === add(5, 3) = 8 multiply(5, 3) = 15 volume(2, 3, 4) = 24 === Lambda with No Arguments === get_pi() = 3.14159 greet() = Hello, World! === Lambda with Default Arguments === power(5) = 25 power(5, 3) = 125 Hello, Alice! Hi, Bob! === Practical: reduce() === Sum of [1, 2, 3, 4, 5] = 15 Product of [1, 2, 3, 4, 5] = 120 Max of [1, 2, 3, 4, 5] = 5main()
53if __name__ == "__main__":54 main()55#@help twoargs
lambda a, b: a + b takes two args. lambda: 42 takes none.
Common lambda patterns
Frequently used lambda idioms.
def main():
print("=== Common Lambda Patterns ===\n")
# Pattern 1: Getter/accessor
print("=== Getter Pattern ===")
users = [
{"name": "Alice", "score": 85},
{"name": "Bob", "score": 92},
{"name": "Charlie", "score": 78}
]
names = list(map(lambda u: u["name"], users))
print(f"Names: {names}")
top_scorer = max(users, key=lambda u: u["score"])
print(f"Top scorer: {top_scorer['name']}")
# Pattern 2: Conditional expression
print("\n=== Conditional Pattern ===")
numbers = [-3, -1, 0, 2, 5]
# Ternary in lambda
signs = list(map(lambda x: "pos" if x > 0 else ("neg" if x < 0 else "zero"),
numbers))
print(f"Numbers: {numbers}")
print(f"Signs: {signs}")
# Pattern 3: Method call
print("\n=== Method Call Pattern ===")
words = ["Hello", "WORLD", "Python"]
lowered = list(map(lambda s: s.lower(), words))
print(f"Lowered: {lowered}")
# Pattern 4: Tuple operations
print("\n=== Tuple Pattern ===")
pairs = [(1, "b"), (3, "a"), (2, "c")]
# Sort by second element
by_second = sorted(pairs, key=lambda p: p[1])
print(f"By second element: {by_second}")
# Pattern 5: Composition
print("\n=== Composition Pattern ===")
# Chain operations
process = lambda x: x.strip().lower().replace(" ", "_")
titles = [" Hello World ", " Python CODE ", " DATA Science "]
slugs = list(map(process, titles))
print(f"Slugs: {slugs}")
if __name__ == "__main__":
main()
users ← [{'name': 'Alice', 'score': 85}, {'name': 'Bob', 'score': 92}, {'name': 'Charlie', 'score': 78}]
1def main():2 print("=== Common Lambda Patterns ===\n")3 4 # Pattern 1: Getter/accessor #?getter5 print("=== Getter Pattern ===")6 users→ [{'name': 'Alice', 'score': 85}, {'name': 'Bob', 'score': 92}, {'name': 'Charlie', 'score': 78}] = [7 {"name": "Alice", "score": 85},8 {"name": "Bob", "score": 92},9 {"name": "Charlie", "score": 78}10 ]11 12 names→ ['Alice', 'Bob', 'Charlie'] = list(map(lambda u: u["name"], users[{'name': 'Alice', 'score': 85}, {'name': 'Bob', 'score': 92}, {'name': 'Charlie', 'score': 78}]))13 print(f"Names: {names['Alice', 'Bob', 'Charlie']}")14 15 top_scorer→ {'name': 'Bob', 'score': 92} = max(users[{'name': 'Alice', 'score': 85}, {'name': 'Bob', 'score': 92}, {'name': 'Charlie', 'score': 78}], key=lambda u: u["score"])16 print(f"Top scorer: {top_scorer['name']Bob}")17 18 # Pattern 2: Conditional expression #?conditional19 print("\n=== Conditional Pattern ===")20 numbers→ [-3, -1, 0, 2, 5] = [-3, -1, 0, 2, 5]21 22 # Ternary in lambda23 signs→ ['neg', 'neg', 'zero', 'pos', 'pos'] = list(map(lambda x: "pos" if x > 0 else ("neg" if x < 0 else "zero"), 24 numbers[-3, -1, 0, 2, 5]))25 print(f"Numbers: {numbers[-3, -1, 0, 2, 5]}")26 print(f"Signs: {signs['neg', 'neg', 'zero', 'pos', 'pos']}")27 28 # Pattern 3: Method call #?method29 print("\n=== Method Call Pattern ===")30 words→ ['Hello', 'WORLD', 'Python'] = ["Hello", "WORLD", "Python"]31 32 lowered→ ['hello', 'world', 'python'] = list(map(lambda s: s.lower(), words['Hello', 'WORLD', 'Python']))33 print(f"Lowered: {lowered['hello', 'world', 'python']}")34 35 # Pattern 4: Tuple operations #?tuple36 print("\n=== Tuple Pattern ===")37 pairs→ [(1, 'b'), (3, 'a'), (2, 'c')] = [(1, "b"), (3, "a"), (2, "c")]38 39 # Sort by second element40 by_second→ [(3, 'a'), (1, 'b'), (2, 'c')] = sorted(pairs[(1, 'b'), (3, 'a'), (2, 'c')], key=lambda p: p[1])41 print(f"By second element: {by_second[(3, 'a'), (1, 'b'), (2, 'c')]}")42 43 # Pattern 5: Composition #?compose44 print("\n=== Composition Pattern ===")45 46 # Chain operations47 process→ <function main.<locals>.<lambda> at ⟨addr A⟩> = lambda x: x.strip().lower().replace(" ", "_")48 49 titles→ [' Hello World ', ' Python CODE ', ' DATA Science '] = [" Hello World ", " Python CODE ", " DATA Science "]50 slugs→ ['hello_world', 'python_code', 'data_science'] = list(map(process<function main.<locals>.<lambda> at ⟨addr A⟩>, titles[' Hello World ', ' Python CODE ', ' DATA Science ']))51 print(f"Slugs: {slugs['hello_world', 'python_code', 'data_science']}")output=== Common Lambda Patterns === === Getter Pattern === Names: ['Alice', 'Bob', 'Charlie'] Top scorer: Bob === Conditional Pattern === Numbers: [-3, -1, 0, 2, 5] Signs: ['neg', 'neg', 'zero', 'pos', 'pos'] === Method Call Pattern === Lowered: ['hello', 'world', 'python'] === Tuple Pattern === By second element: [(3, 'a'), (1, 'b'), (2, 'c')] === Composition Pattern === Slugs: ['hello_world', 'python_code', 'data_science']main()
53if __name__ == "__main__":54 main()55#@help getter
Key extraction, default values, and simple transformations are common uses.
Exercise: limitations.py
Explore when NOT to use lambda - prefer def for complex logic