Python Functions Cheat Sheet: def, args, lambda, scope
def name(parameters): and return a result; use default values, *args and **kwargs for flexible arguments, lambda for tiny one-expression functions, and nonlocal/global only when you must rebind outer names.Functions let you name a piece of logic and reuse it. This cheat sheet shows how to define and call them, pass flexible arguments, use lambdas with map, filter and sorted, and understand scope, recursion and type hints. Results come from running the code.
For the explanations behind each row, see Python functions, function arguments and *args and **kwargs.
Python function definition and calling cheat sheet
| Task | Code | Result |
|---|---|---|
| Call with positional arguments | add(2, 3) | 5 |
| Call with keyword arguments | add(b=1, a=5) | 6 |
| Use a default value | greet() | 'Hi friend!' |
| Override one default by name | greet(punct="?") | 'Hi friend?' |
| Function with no return gives None | noop() | None |
| Return several values | stats([4, 9, 2]) | (2, 9) |
| Unpack returned values | lo, hi = stats([4, 9, 2]); hi - lo | 7 |
| Function is an object | type(add).__name__ | 'function' |
| Read the function name | add.__name__ | 'add' |
| Call a function stored in a list | [f(1, 2) for f in (add, max)] | [3, 2] |
| print vs return | print("x") is None | True |
Python *args and **kwargs cheat sheet
| Task | Code | Result |
|---|---|---|
| Collect positional extras | total(1, 2, 3) | (6, {}) |
| Collect keyword extras | total(1, mode="fast") | (1, {'mode': 'fast'}) |
| Unpack a list into arguments | add(*[4, 5]) | 9 |
| Unpack a dict into arguments | add(**{"a": 1, "b": 2}) | 3 |
| Mix both | total(*[1, 2], **{"k": 0}) | (3, {'k': 0}) |
| Keyword-only after * | (lambda *, x: x)(x=3) | 3 |
| Positional-only before / | (lambda a, /: a)(7) | 7 |
| Too few arguments fails | add(1) | TypeError: add() missing 1 required positional argument: 'b' |
| Too many arguments fails | add(1, 2, 3) | TypeError: add() takes 2 positional arguments but 3 were given |
| Unknown keyword fails | add(1, c=2) | TypeError: add() got an unexpected keyword argument 'c' |
| Max of several arguments | max(3, 9, 4) | 9 |
Python lambda, map, filter and sorted with key
| Task | Code | Result |
|---|---|---|
| Lambda call | (lambda x: x * 2)(4) | 8 |
| Lambda with two arguments | (lambda a, b: a + b)(2, 3) | 5 |
| map with a function | list(map(len, ["a", "bb", "ccc"])) | [1, 2, 3] |
| map with a lambda | list(map(lambda x: x + 1, [1, 2, 3])) | [2, 3, 4] |
| filter with a lambda | list(filter(lambda x: x % 2, [1, 2, 3, 4])) | [1, 3] |
| reduce to one value | functools.reduce(lambda a, b: a * b, [1, 2, 3, 4]) | 24 |
| Sort by length | sorted(["pear", "fig", "apple"], key=len) | ['fig', 'pear', 'apple'] |
| Sort by a tuple field | sorted([("a", 3), ("b", 1)], key=lambda t: t[1]) | [('b', 1), ('a', 3)] |
| Largest by key | max(["aa", "b", "cccc"], key=len) | 'cccc' |
| Comprehension instead of map | [x + 1 for x in [1, 2, 3]] | [2, 3, 4] |
| Immediately sum a generator | sum(x * x for x in range(4)) | 14 |
Python scope, recursion and closures cheat sheet
| Task | Code | Result |
|---|---|---|
| Local variables stay inside | def f(): x = 1 | x exists only while f() runs; outside it raises NameError |
| global rebinds a module variable | global counter | lets a function assign to the module-level counter |
| nonlocal rebinds an outer variable | nonlocal count | lets an inner function assign to the enclosing function's count |
| Recursive factorial | fact(5) | 120 |
| Recursive sum of a list | rsum([1, 2, 3]) | 6 |
| Fibonacci recursion | fib(7) | 13 |
| Closure remembers a value | make_adder(10)(5) | 15 |
| Recursion limit hit | def loop(): return loop() | RecursionError: maximum recursion depth exceeded |
| Using a local before assignment | def f(): print(v); v = 1 | UnboundLocalError when f() runs |
| Decorator syntax | @timer | same as fn = timer(fn) |
| Tower of Hanoi moves for n disks | 2 ** 3 - 1 | 7 |
Python type hints and docstrings cheat sheet
| Task | Code | Result |
|---|---|---|
| Annotate parameters and return | def add(a: int, b: int) -> int: | hints document types; Python does not enforce them at runtime |
| Optional value | def find(x) -> str | None: | str | None means a string or None (Python 3.10+) |
| List of ints | nums: list[int] = [1, 2] | built-in generics need no import since Python 3.9 |
| Dict of str to float | prices: dict[str, float] = {} | documents key and value types |
| Hints do not stop wrong types | add2("a", "b") | 'ab' |
| Read the annotations | add3.__annotations__ | {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>} |
| Docstring | def f(): """Explain.""" | the first string literal becomes f.__doc__ |
| Read a docstring | f.__doc__ | 'Explain.' |
| Default mutable argument trap | def add_to(x, bag=[]): | the same list is reused on every call, so use None and create the list inside |
| Check argument type | isinstance(3, (int, float)) | True |
Python built-in functions you call every day
| Task | Code | Result |
|---|---|---|
| print several values | print(1, "a", sep="-") | 1-a |
| Length of a collection | len([1, 2, 3]) | 3 |
| Absolute value | abs(-7.5) | 7.5 |
| Power with pow | pow(2, 5) | 32 |
| Round half to even | round(2.5), round(3.5) | (2, 4) |
| Sum with start value | sum([1, 2], 10) | 13 |
| Smallest of several | min(4, 1, 7) | 1 |
| Sort any iterable | sorted("cab") | ['a', 'b', 'c'] |
| Reverse any sequence | list(reversed(range(3))) | [2, 1, 0] |
| Enumerate from 1 | list(enumerate(["a", "b"], 1)) | [(1, 'a'), (2, 'b')] |
| Read a line of input | name = input("Name: ") | waits for the user and returns text |
| Open a file | open("data.txt") | returns a file object (raises FileNotFoundError if missing) |
Examples you can run
Press Run, then edit the code and run it again.
Default, keyword and variable arguments
One function using a default value, *args and **kwargs.
def order(item, qty=1, *extras, **notes):
return item, qty, extras, notes
print(order("tea"))
print(order("tea", 2, "milk", sugar=0))Expected output('tea', 1, (), {})
('tea', 2, ('milk',), {'sugar': 0})
Closure and sorted with a key
A function that returns a function, plus sorting records by a field.
def make_discount(rate):
return lambda price: round(price * (1 - rate), 2)
ten_off = make_discount(0.10)
print(ten_off(80))
staff = [("Ravi", 31), ("Asha", 25)]
print(sorted(staff, key=lambda p: p[1]))Expected output72.0
[('Asha', 25), ('Ravi', 31)]
Python Functions Cheat Sheet: def, args, lambda, scope: questions people ask
What is the difference between print and return in a Python function?
print() only shows a value on screen, while return hands the value back to the caller so it can be stored or used. A function without return gives back None.
What do *args and **kwargs mean in Python?
*args collects extra positional arguments into a tuple and **kwargs collects extra keyword arguments into a dictionary. The names args and kwargs are just convention.
Why should I not use a list as a default argument?
A default value is created once when the function is defined, so a default list is shared between calls. Use None as the default and create a new list inside the function.
Keep learning
Step-by-step lessons:
Python FunctionsPython Function ArgumentsPython *args and **kwargs
Related:
Python Cheat Sheet (Python 3.13 Quick Reference)Python OOP Cheat Sheet: Classes, Inheritance, Dunder MethodsPython print() vs return: What Is the Difference?Python Function vs Method: What Is the Difference?Python Lambda Functions
More in core python:
Python Cheat Sheet (Python 3.13 Quick Reference)Python String Cheat Sheet: Methods and FormattingPython List Cheat Sheet: Methods and ExamplesPython Dictionary Cheat Sheet: Methods and ExamplesPython Control Flow Cheat Sheet: if, for, while, matchPython OOP Cheat Sheet: Classes, Inheritance, Dunder MethodsPython Regex Cheat Sheet (re Module Quick Reference)Python File Handling Cheat Sheet: open, read, write, CSV, JSON See all →