Level: Intermediate | Prerequisite: Week 9 Basics (Basic Functions)
Learning Goals
- Accepts variable arguments with
*args,**kwargs - Uses lambda functions
- Utilizes higher-order functions (
map,filter,sortedwith key) - Understands the operation of closures
1. *args, **kwargs
Variable number of arguments.
def add_all(*args): #args is a tuple
return sum(args)
print(add_all(1, 2, 3)) # 6
print(add_all(1, 2, 3, 4, 5)) # 15
def info(**kwargs): #kwargs is a dictionary
for k, v in kwargs.items():
print(f"{k}: {v}")
info(name="Hong Gil-dong", age=20)
Combinations also possible:
def f(a, b, *args, **kwargs):
...
2. Lambda Functions
Anonymous one-line functions. Suitable for immediate use.
square = lambda x: x * x
print(square(5)) # 25
#Usually passed as an argument to another function
nums = [1, 2, 3, 4, 5]
print(list(map(lambda x: x * 2, nums))) # [2, 4, 6, 8, 10]
3. Higher-Order Functions
Functions that take other functions as arguments.
nums = [1, 2, 3, 4, 5]
#map: transform
print(list(map(lambda x: x * x, nums))) # [1, 4, 9, 16, 25]
#filter: filtering
print(list(filter(lambda x: x % 2, nums))) # [1, 3, 5]
# sorted with key
people = [("Alice", 30), ("Bob", 25), ("Charlie", 28)]
people.sort(key=lambda p: p[1])
print(people)
4. Closures
Functions defined inside another function remember outer variables.
def make_counter():
count = 0
def inc():
nonlocal count #nonlocal is needed when modifying an outer variable
count += 1
return count
return inc
c = make_counter()
print(c(), c(), c()) # 1 2 3
Key Examples (examples/)
| File | Content |
|---|---|
01_args_kwargs.py |
Variable arguments |
02_lambda.py |
Lambda functions |
03_higher_order.py |
map / filter / sorted |
04_closure.py |
Closures and nonlocal |
⚠️ Common Mistakes
- Position of
*args— After regular parameters, before**kwargs. - Too much logic in lambda — If it gets long, just use
def. Lambdas are one line. - Confusion between
sortedandsort—sorted()is a new list,list.sort()modifies in place. - Omitting
nonlocalin closures — Using onlycount += 1causes UnboundLocalError.
❓ FAQ
Q1. When should *args be used?
A. When the number of arguments is not fixed. Example: print, max(1, 2, 3, ...).
Q2. Performance difference between lambda and regular functions? A. Almost none. Lambda is syntactic sugar for readability and conciseness.
Q3. Where are closures used? A. Decorators, callbacks, functions with state. A lightweight alternative to objects.
📝 Exercises (exercises/)
exercise1.md—stats(*nums)Mean/Varianceexercise2.md— Sorting student scores (sorted with key)exercise3.md—make_countercall counter
Next Week
Week 2. Comprehensions and Generators — Concise repetitive expressions