Cheat sheetCore Python

Python Functions Cheat Sheet: def, args, lambda, scope

Short answer
Define a Python function with 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

Assume the helper functions `add(a, b)`, `greet(name="friend", punct="!")`, `total(*nums, **opts)`, `noop()` and `stats(xs)` are defined.
TaskCodeResult
Call with positional argumentsadd(2, 3)5
Call with keyword argumentsadd(b=1, a=5)6
Use a default valuegreet()'Hi friend!'
Override one default by namegreet(punct="?")'Hi friend?'
Function with no return gives Nonenoop()None
Return several valuesstats([4, 9, 2])(2, 9)
Unpack returned valueslo, hi = stats([4, 9, 2]); hi - lo7
Function is an objecttype(add).__name__'function'
Read the function nameadd.__name__'add'
Call a function stored in a list[f(1, 2) for f in (add, max)][3, 2]
print vs returnprint("x") is NoneTrue

Python *args and **kwargs cheat sheet

TaskCodeResult
Collect positional extrastotal(1, 2, 3)(6, {})
Collect keyword extrastotal(1, mode="fast")(1, {'mode': 'fast'})
Unpack a list into argumentsadd(*[4, 5])9
Unpack a dict into argumentsadd(**{"a": 1, "b": 2})3
Mix bothtotal(*[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 failsadd(1)TypeError: add() missing 1 required positional argument: 'b'
Too many arguments failsadd(1, 2, 3)TypeError: add() takes 2 positional arguments but 3 were given
Unknown keyword failsadd(1, c=2)TypeError: add() got an unexpected keyword argument 'c'
Max of several argumentsmax(3, 9, 4)9

Python lambda, map, filter and sorted with key

TaskCodeResult
Lambda call(lambda x: x * 2)(4)8
Lambda with two arguments(lambda a, b: a + b)(2, 3)5
map with a functionlist(map(len, ["a", "bb", "ccc"]))[1, 2, 3]
map with a lambdalist(map(lambda x: x + 1, [1, 2, 3]))[2, 3, 4]
filter with a lambdalist(filter(lambda x: x % 2, [1, 2, 3, 4]))[1, 3]
reduce to one valuefunctools.reduce(lambda a, b: a * b, [1, 2, 3, 4])24
Sort by lengthsorted(["pear", "fig", "apple"], key=len)['fig', 'pear', 'apple']
Sort by a tuple fieldsorted([("a", 3), ("b", 1)], key=lambda t: t[1])[('b', 1), ('a', 3)]
Largest by keymax(["aa", "b", "cccc"], key=len)'cccc'
Comprehension instead of map[x + 1 for x in [1, 2, 3]][2, 3, 4]
Immediately sum a generatorsum(x * x for x in range(4))14

Python scope, recursion and closures cheat sheet

TaskCodeResult
Local variables stay insidedef f(): x = 1x exists only while f() runs; outside it raises NameError
global rebinds a module variableglobal counterlets a function assign to the module-level counter
nonlocal rebinds an outer variablenonlocal countlets an inner function assign to the enclosing function's count
Recursive factorialfact(5)120
Recursive sum of a listrsum([1, 2, 3])6
Fibonacci recursionfib(7)13
Closure remembers a valuemake_adder(10)(5)15
Recursion limit hitdef loop(): return loop()RecursionError: maximum recursion depth exceeded
Using a local before assignmentdef f(): print(v); v = 1UnboundLocalError when f() runs
Decorator syntax@timersame as fn = timer(fn)
Tower of Hanoi moves for n disks2 ** 3 - 17

Python type hints and docstrings cheat sheet

TaskCodeResult
Annotate parameters and returndef add(a: int, b: int) -> int:hints document types; Python does not enforce them at runtime
Optional valuedef find(x) -> str | None:str | None means a string or None (Python 3.10+)
List of intsnums: list[int] = [1, 2]built-in generics need no import since Python 3.9
Dict of str to floatprices: dict[str, float] = {}documents key and value types
Hints do not stop wrong typesadd2("a", "b")'ab'
Read the annotationsadd3.__annotations__{'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}
Docstringdef f(): """Explain."""the first string literal becomes f.__doc__
Read a docstringf.__doc__'Explain.'
Default mutable argument trapdef add_to(x, bag=[]):the same list is reused on every call, so use None and create the list inside
Check argument typeisinstance(3, (int, float))True

Python built-in functions you call every day

TaskCodeResult
print several valuesprint(1, "a", sep="-")1-a
Length of a collectionlen([1, 2, 3])3
Absolute valueabs(-7.5)7.5
Power with powpow(2, 5)32
Round half to evenround(2.5), round(3.5)(2, 4)
Sum with start valuesum([1, 2], 10)13
Smallest of severalmin(4, 1, 7)1
Sort any iterablesorted("cab")['a', 'b', 'c']
Reverse any sequencelist(reversed(range(3)))[2, 1, 0]
Enumerate from 1list(enumerate(["a", "b"], 1))[(1, 'a'), (2, 'b')]
Read a line of inputname = input("Name: ")waits for the user and returns text
Open a fileopen("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.

Default, keyword and variable arguments
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.

Closure and sorted with a key
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 →