Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Common Types of Functions in Python

1 min read .
Common Types of Functions in Python

Python functions range from ordinary def functions to lambdas, generators, methods, and asynchronous functions. Understanding the differences helps you choose the clearest abstraction for each task.

1. Built-in Functions

Python includes many functions that are available without imports:

print("Hello, world!")
print(len([1, 2, 3]))
print(sum([1, 2, 3]))

Other examples include type(), range(), enumerate(), zip(), min(), and max().

2. User-Defined Functions

Use def for ordinary reusable behavior:

def greet(name):
    return f"Hello, {name}!"

Functions can accept positional and keyword arguments, define defaults, and return any Python object.

3. Variable Positional Arguments with *args

def add_numbers(*args):
    return sum(args)


print(add_numbers(1, 2, 3, 4))

Inside the function, args is a tuple containing the extra positional arguments.

4. Variable Keyword Arguments with **kwargs

def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")


print_info(name="Alice", age=30)

Inside the function, kwargs is a dictionary.

5. Lambda Functions

A lambda is a small anonymous function containing a single expression:

square = lambda value: value * value
print(square(5))

Lambdas are most useful when a short function is needed inline, for example as a sorting key:

users = [{"name": "Bob", "age": 30}, {"name": "Alice", "age": 25}]
users.sort(key=lambda user: user["age"])

For multi-step logic, use def instead.

6. Generator Functions

A function containing yield returns a generator iterator:

def countdown(start):
    while start > 0:
        yield start
        start -= 1


for number in countdown(3):
    print(number)

Generators produce values lazily and are useful for streams or large datasets.

7. Methods

Functions defined inside classes become methods according to how they are declared:

class Greeter:
    def greet(self, name):
        return f"Hello, {name}!"

Python also supports class methods and static methods through decorators.

8. Async Functions

async def defines a coroutine function:

import asyncio


async def main():
    await asyncio.sleep(1)
    print("done")


asyncio.run(main())

Async functions are useful for concurrent I/O when the libraries involved support asynchronous operation.

Conclusion

Use ordinary def functions by default. Reach for lambdas for tiny inline expressions, generators for lazy sequences, methods for class behavior, and async def for asynchronous I/O workflows. The simplest function type that clearly communicates the intent is usually the best choice.

Related Posts

chevron-up