Functions are the foundation of reusable and maintainable code. At the beginner level, you learned how to define and call functions. In this lesson, we take it further by exploring advanced function features that are widely used in real-world Python applications.
You will learn:
β Flexible arguments with *args and **kwargs
β Default, positional, and keyword arguments
β Lambda (anonymous) functions
β Higher-order functions (map, filter, reduce)
β Introduction to decorators
These tools will allow you to write cleaner, more dynamic, and reusable code.
def greet(name="Guest"):
print("Hello", name)
greet() # Hello Guest
greet("Ali") # Hello Alidef info(name, age):
print(name, age)
info("Sara", 25) # positional
info(age=25, name="Sara") # keyword*args allows a function to accept any number of positional arguments.
def add_numbers(*args):
total = 0
for n in args:
total += n
return total
print(add_numbers(1, 2, 3, 4)) # 10π‘ args is a tuple.
**kwargs allows a function to accept any number of keyword arguments.
def display_info(**kwargs):
for key, value in kwargs.items():
print(key, ":", value)
display_info(name="Ali", age=22)π‘ kwargs is a dictionary.
A lambda is a small, one-line function.
square = lambda x: x * x
print(square(5)) # 25map:nums = [1, 2, 3]
result = list(map(lambda x: x*2, nums))
print(result)These are functions that take other functions as arguments.
Applies a function to each item:
nums = [1, 2, 3]
result = list(map(lambda x: x * 2, nums))Filters elements:
nums = [1, 2, 3, 4]
evens = list(filter(lambda x: x % 2 == 0, nums))Requires functools:
from functools import reduce
nums = [1, 2, 3, 4]
result = reduce(lambda x, y: x + y, nums)A decorator is a function that wraps another function.
def my_decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper@my_decorator
def say_hello():
print("Hello!")
say_hello()Before function
Hello!
After function
In this lesson, youβve unlocked some of Pythonβs most powerful function features:
These concepts are widely used in frameworks like Django, Flask, and FastAPI.