Module 6: Python FunctionsBeginner20 min read
*args, **kwargs & Lambda Functions
Accept variable numbers of arguments and write concise anonymous lambda functions.
Key Takeaways & Core Concepts
*args: Receives positional arguments as a tuple.**kwargs: Receives keyword arguments as a dictionary.- 2
*args, **kwargs & Lambda Functions
### Variable Arguments: args and *kwargs
When you don't know in advance how many arguments will be passed to a function:
*args: Receives positional arguments as a tuple.**kwargs: Receives keyword arguments as a dictionary.
PYTHON Code Example
1def build_profile(username, *skills, **metadata):
2 print("User:", username)
3 print("Skills:", skills)
4 print("Metadata:", metadata)
5
6build_profile("alex_coder", "Python", "SQL", "Docker", country="India", role="SDE")
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
6 lines
#### Lambda Functions A lambda function is an anonymous inline function defined with the lambda keyword:
PYTHON Code Example
1square = lambda x: x ** 2
2print(square(8)) # 64
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
2 lines
Sorting with Lambda Key
1students = [
2 {"name": "Zoya", "grade": 88},
3 {"name": "Rohan", "grade": 95},
4 {"name": "Ananya", "grade": 91}
5]
6
7students.sort(key=lambda s: s["grade"], reverse=True)
8for s in students:
9 print(f"{s['name']}: {s['grade']}")
Click code or "Edit Code" to edit
Interactive Code Block•Tab = 4 spaces•Ctrl + Enter = Run
9 lines
Note: The lambda extracts the 'grade' value as the comparison sort key.
Practice & AssessmentPython Programming Tutorial
Test Your Understanding
Reinforce core concepts with interactive multiple-choice questions, live coding challenges, and top technical interview questions.
Your Current Score
0 / 0 correct(0 attempted)