Skip to content
Laviyx Learn

Try

Python Functions Cheat Sheet

Parameters, defaults, *args, **kwargs, lambdas, and scope rules.

Updated

# → value shows what an expression returns. # name → value shows what a variable holds after that line.

Defining and calling#

Python
def greet(name, greeting="Hello"):
    """Return a greeting."""          # docstring
    return f"{greeting}, {name}!"

greet("Asha")                         # → 'Hello, Asha!'
greet("Ravi", "Welcome")              # → 'Welcome, Ravi!'
greet(greeting="Hi", name="Meera")    # → 'Hi, Meera!'

A function without return returns None. return ends the function immediately.

Kinds of parameters#

Python
def f(a, b=2, *args, key, flag=False, **kwargs):
    return a, b, args, key, flag, kwargs

f(1, key="k")                         # → (1, 2, (), 'k', False, {})
f(1, 5, 6, 7, key="k", x=9)           # → (1, 5, (6, 7), 'k', False, {'x': 9})
ParameterMeaning
arequired positional
b=2optional, with a default
*argsextra positional values, collected into a tuple
key (after *args or a bare *)keyword-only: must be passed by name
**kwargsextra keyword values, collected into a dict

Order: required → defaults → *args → keyword-only → **kwargs.

Mutable default trap#

Python
def add(item, items=None):            # never items=[]
    if items is None:
        items = []
    items.append(item)
    return items

add(1)                                # → [1]
add(2)                                # → [2]

Defaults are created once, when the function is defined, so a [] default would be shared by every call.

Returning several values#

Python
def min_max(nums):
    return min(nums), max(nums)       # returns a tuple

low, high = min_max([4, 9, 1])        # low → 1

Unpacking arguments#

Python
def add3(a, b, c):
    return a + b + c

add3(*[1, 2, 3])                      # → 6
add3(**{"a": 1, "b": 2, "c": 3})      # → 6

Lambda functions#

Python
square = lambda n: n * n
square(4)                             # → 16

people = [("Asha", 21), ("Ravi", 25), ("Meera", 19)]
sorted(people, key=lambda p: p[1])    # → [('Meera', 19), ('Asha', 21), ('Ravi', 25)]
max(people, key=lambda p: p[1])       # → ('Ravi', 25)
sorted(["b", "A", "c"], key=str.lower)   # → ['A', 'b', 'c']

One expression only, no statements. Use def for anything longer or reused.

Scope (LEGB)#

Python looks up names in this order: Local → Enclosing → Global → Built-in.

Python
count = 0

def bump():
    global count                      # needed to *assign* a global
    count += 1

bump()                                # count → 1

def counter():
    n = 0
    def inc():
        nonlocal n                    # assign to the enclosing function's n
        n += 1
        return n
    return inc

tick = counter()
tick(), tick()                        # → (1, 2)

Assigning to a name anywhere inside a function makes it local there. Prefer returning values over global.

Recursion#

Python
def factorial(n):
    if n <= 1:                        # base case
        return 1
    return n * factorial(n - 1)       # recursive case

factorial(5)                          # → 120

Default recursion limit: about 1,000 calls (sys.getrecursionlimit()).

Decorators#

Python
from functools import wraps

def shout(func):
    @wraps(func)                      # keep the original name and docstring
    def wrapper(*args, **kwargs):
        return func(*args, **kwargs).upper()
    return wrapper

@shout                                # same as: hello = shout(hello)
def hello(name):
    return f"hi {name}"

hello("asha")                         # → 'HI ASHA'
hello.__name__                        # → 'hello'
Python
from functools import lru_cache

@lru_cache(maxsize=None)              # remember previous results
def fib(n):
    return n if n < 2 else fib(n - 1) + fib(n - 2)

fib(50)                               # → 12586269025

Generators#

Python
def countdown(n):
    while n > 0:
        yield n                       # pause and hand back a value
        n -= 1

list(countdown(3))                    # → [3, 2, 1]
sum(n * n for n in range(4))          # → 14

Values are produced lazily, one at a time, and a generator can be consumed only once.

Type hints#

Python
def area(width: float, height: float = 1.0) -> float:
    return width * height

area(3, 2.5)                          # → 7.5

Hints document intent for editors and tools like mypy; Python does not enforce them at runtime.

Built-in functions worth knowing#

FunctionExampleResult
lenlen("hi")2
sum, min, maxmax([3, 9, 2])9
sortedsorted("cba")['a', 'b', 'c']
enumeratelist(enumerate("ab"))[(0, 'a'), (1, 'b')]
ziplist(zip("ab", [1, 2]))[('a', 1), ('b', 2)]
maplist(map(str, [1, 2]))['1', '2']
filterlist(filter(None, [0, 1, 2]))[1, 2]
any, allany([0, 3]), all([0, 3])True, False
roundround(3.14159, 2)3.14
isinstanceisinstance(5, int)True

Full lessons: Functions, Parameters, Scope, Lambda, Recursion, Decorators, Generators.

Want the full explanations? Go to the Learn Python course →