Advanced Functions: *args, **kwargs & Lambda
Level up your functional programming. Master arbitrary arguments, keyword arguments, and write elegant one-line Lambda functions.
Flexible Parameters
Sometimes you don't know exactly how many arguments a user might pass into your function. Python handles this elegantly with arbitrary arguments.
*args (Non-Keyword Arguments)
By adding an asterisk * before a parameter, Python scoops up all remaining arguments and packs them into a Tuple.
def multiply_all(*numbers):
total = 1
for num in numbers:
total *= num
return total
print(multiply_all(2, 3, 4)) # Result: 24**kwargs (Keyword Arguments)
Adding two asterisks ** scoops up all remaining named arguments and packs them into a Dictionary.
def build_profile(name, **user_info):
profile = {"name": name}
profile.update(user_info)
return profile
user = build_profile("Alice", role="Admin", age=30)Lambda: The Anonymous Function
Lambda functions are tiny, one-line functions that don't even have a name. They are heavily used when you need to pass a simple, temporary function into another function (like sorting a complex list).
# Syntax: lambda arguments : expression
multiply = lambda a, b: a * b
print(multiply(5, 6)) # 30