What is a lambda function in Python?
An anonymous function defined as: lambda arguments: expression. Supports multiple arguments but only one expression.
Where are lambda functions commonly used?
As short, one-time functions for map(), filter(), reduce(), or sorting with key parameter.
How to sort a list of tuples by second element using lambda?
people.sort(key=lambda x: x[1])
What is a key advantage of lambdas over regular functions?
Conciseness when a full def function would be overkill.
Can all functions be converted to lambdas?
No, lambdas are limited to a single expression.
What is a callable in Python?
Any object that can be called like a function, e.g., functions, methods, classes, or instances with __call__ defined.
How to make a class instance callable?
Define a __call__(self, …) method in the class.
Why use callable objects?
To store state/configuration and allow simpler function-like syntax while preserving object data.
What is a decorator?
A function that takes another function and returns a modified version, allowing behavior to be added before and/or after the wrapped function runs.
Provide the basic syntax of a decorator.
def decorator(func):
def wrapper(args, **kwargs):
# code before
result = func(args, **kwargs)
# code after
return result
return wrapper
@decorator
def my_func(): …
What is @decorator syntactic sugar for?
my_func = decorator(my_func)
Give an example of a logging decorator.
def log_decorator(func):
def wrapper(args, **kwargs):
print(f”Starting {func.__name__}”)
result = func(args, **kwargs)
print(f”Ending {func.__name__}”)
return result
return wrapper
Name some built-in decorators in Python.
@staticmethod, @classmethod, @property
Which functools decorators are particularly useful?
@cache (caches results), @wraps (preserves metadata), @singledispatch (type-based function overloading).
What are asynchronous functions?
Functions declared with async def that can be paused and resumed, allowing concurrent, non-blocking execution.
What is a coroutine?
A special function (async def) that can pause (await) and resume, yielding control back to the event loop.
What keyword is used inside coroutines to pause execution?
await
What is an event loop in asyncio?
The mechanism that schedules and runs coroutines. Typically started with asyncio.run(main()).
Which functions schedule or group coroutines?
asyncio.create_task() schedules a coroutine; asyncio.gather() runs multiple coroutines concurrently and waits for all.
How is async different from multiprocessing?
Async runs in one process and one CPU core, focusing on non-blocking I/O; multiprocessing runs code truly in parallel on multiple cores.
Give an example of creating and running a single async task.
async def my_task():
await asyncio.sleep(2)
print(‘Task completed’)
async def main():
task = asyncio.create_task(my_task())
print(‘Main continues…’)
await asyncio.sleep(3)
asyncio.run(main())