Interview Q&A / Python

INTERVIEW Q&A · 81 QUESTIONS

Python interview questions

Lists, dictionaries, generators, decorators and the Python questions asked in service-company and data roles.

  1. What are *args and **kwargs in Python?

    In a function definition, *args collects any extra positional arguments into a tuple, and **kwargs collects any extra keyword arguments into a dict. They let a function accept a variable number of inputs. The same * and ** symbols also unpack a list or dict when calling a function.

    BeginnerIn-depth3 min read
  2. What are mutable and immutable objects in Python, and why is a mutable default argument a bug?

    Mutable objects such as lists, dicts and sets can change in place; immutable ones such as int, str and tuple cannot. Default arguments are evaluated once, when the function is defined, so a list used as a default is shared across every call. Use None as the default and create the list inside the function.

    BeginnerIn-depth3 min read
  3. What is a decorator in Python and how do you write one?

    A decorator is a function that takes another function, wraps it with extra behaviour, and returns the wrapped version. Writing @my_decorator above a function is shorthand for func = my_decorator(func). They are used for logging, timing, caching and access checks without changing the original function's code.

    IntermediateIn-depth3 min read
  4. What is a lambda function in Python, and what are its limits?

    A lambda is a small anonymous function written as lambda args: expression. It contains a single expression, returns its value automatically and cannot hold statements. It is handy as a short key or callback.

    BeginnerQuick answer1 min read
  5. What is the LEGB rule in Python?

    LEGB is the order in which Python looks up a name: Local, Enclosing (outer functions), Global (module), then Built-in. The first scope that contains the name wins, and if none do, Python raises NameError.

    BeginnerQuick answer1 min read
  6. What do the / and * markers in a Python function signature mean?

    Parameters before / are positional-only, so callers cannot pass them by name. Parameters after a bare * are keyword-only, so callers must pass them by name. Both make an API clearer and safer to change.

    IntermediateQuick answer1 min read
  7. What is a closure in Python?

    A closure is an inner function that remembers variables from the enclosing function even after that outer function has finished. It is how Python implements function factories and decorators with private state.

    IntermediateQuick answer1 min read
  8. What is the difference between the global and nonlocal keywords in Python?

    global makes a name inside a function refer to the module-level variable. nonlocal makes it refer to a variable in the nearest enclosing function. Both are needed only when you assign to the name, not when you just read it.

    IntermediateQuick answer1 min read