4. Functions, Dictionaries & Data Drills
Flexible Functions: *args, **kwargs, Lambda & Type Hints
Go beyond basic def functions: accept unlimited arguments with *args and **kwargs, write concise lambda sorting keys, document functions with docstrings, and add readable type hints.
- Accept flexible numbers of inputs using *args and keyword **kwargs
- Sort lists of dictionaries cleanly with lambda functions and key=
- Make real-world functions easier to read using docstrings and Python type hints
Earlier you learned how to define crisp functions with fixed parameters like def apply_discount(price, percent=10):. That handles most everyday cases—yet the moment you read real Python projects or libraries, you will quickly run into four extra function superpowers: *args, **kwargs, lambda, and type hints.
Accepting Unlimited Positional Inputs (*args)
Imagine writing a helper add_all(...) that should work whether someone passes 2 numbers, 4 numbers, or 10 numbers—without wrapping them in square brackets [...] first.
Putting one asterisk (*) before a parameter name packs any number of positional inputs into a tuple:
def sum_scores(*scores):
print("Received:", scores) # Tuple: (10, 25, 15)
return sum(scores)
print(sum_scores(10, 25)) # 35
print(sum_scores(10, 25, 15, 5)) # 55Inside sum_scores, scores behaves just like a normal tuple you can loop over or pass directly to sum(). (Notice *args is just the popular convention—you can name it *scores or *items so your code reads clearly!)
Accepting Named Extra Settings (**kwargs)
Putting two asterisks (**) before a parameter gathers arbitrary key=value keyword arguments into a dictionary:
def create_profile(username, **details):
print(f"User: {username}")
for key, value in details.items():
print(f" - {key}: {value}")
create_profile("alex", role="Student", city="Austin", plan="Free")Libraries like Matplotlib, Flask, and Django use **kwargs constantly so callers can pass optional settings (color="indigo", timeout=10) without needing 25 separate parameters in the header.
One-Line Throwaway Functions (lambda) & Custom Sorting
Sometimes you need a tiny, throwaway function once—most often to tell Python's sorted() which field inside each dictionary to sort by!
Instead of writing a separate multi-line def just to return student["score"], Python offers lambda parameters: expression:
students = [
{"name": "Maya", "score": 88},
{"name": "Liam", "score": 96},
{"name": "Noah", "score": 79},
]
# Sort highest score first using a one-line lambda key
ranked = sorted(students, key=lambda s: s["score"], reverse=True)
for s in ranked:
print(s["name"], s["score"])Read lambda s: s["score"] like English: "Given each student dictionary s, look up and compare s['score']."
Save lambda strictly for tiny single-expression callbacks inside sorted(), min(), or max(). Whenever logic takes multiple lines or deserves a descriptive name, always write a clear def function!
Clear Contracts: Type Hints & Docstrings
As projects grow past 100 lines, remembering whether discount expects an int (20) or a float (0.20), and what the function returns, gets tricky. Adding type hints (name: str, -> float) and a concise docstring ("""...""") documents your intent right in the code—and lets VS Code catch mistakes before you even run your script!
def calculate_tax(amount: float, rate: float = 0.08) -> float:
"""Return total cost after applying the given tax rate."""
return round(amount * (1 + rate), 2)
print(calculate_tax(100.0)) # 108.0
print(calculate_tax(100.0, 0.15)) # 115.0Python treats type hints as helpful labels rather than strict runtime blockers—so existing code stays fast while your editor gains smart autocomplete.
Try It Yourself in the Playground
Test *args, **kwargs, type hints, and lambda sorting live below—try adding "active": True or changing reverse=True to sort lowest price first:
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Use sorted(..., key=lambda w: len(w)) to sort words = ["python", "ai", "terminal", "sql"] from shortest word to longest word (['ai', 'sql', 'python', 'terminal']).
Quick Checkpoints
What data type does Python pack arguments into when a function uses *scores?
Why do Python developers frequently pass lambda item: item['price'] to sorted()?