Day 9: Advanced Functions
*args (Variable Positional Arguments)
def total(*args):
return sum(args)
print(total(1, 2, 3)) # 6
print(total(10, 20, 30, 40)) # 100
**kwargs (Variable Keyword Arguments)
def build_profile(**kwargs):
return {k: v for k, v in kwargs.items()}
profile = build_profile(name="Alice", age=25, city="Seoul")
print(profile) # {'name': 'Alice', 'age': 25, 'city': 'Seoul'}
Argument Order Rules
def func(pos, *args, key="default", **kwargs):
print(f"pos={pos}, args={args}, key={key}, kwargs={kwargs}")
func(1, 2, 3, key="custom", extra="value")
# pos=1, args=(2, 3), key=custom, kwargs={'extra': 'value'}
Lambda Functions
Anonymous one-line functions.
square = lambda x: x ** 2
add = lambda a, b: a + b
print(square(5)) # 25
print(add(3, 4)) # 7
Higher-Order Functions: map, filter, sorted
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # [2, 4, 6, 8, 10]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # [2, 4]
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
ranked = sorted(students, key=lambda s: s[1], reverse=True)
print(ranked) # [('Bob', 92), ('Alice', 85), ('Charlie', 78)]
Today’s Exercises
- Create a function using
*argsthat takes multiple lists and merges them into one. - Use
mapandlambdato create a list of word lengths from a list of strings. - Use
filterto extract items from a list of dictionaries that meet a specific condition.