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. Does the loop variable of a list comprehension leak into the surrounding scope in Python 3?

    No. In Python 3 a comprehension has its own scope, so its loop variable does not leak. A normal for loop does leave its variable behind. In Python 2, list comprehensions did leak.

    IntermediateQuick answer1 min read
  2. 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
  3. Why does this code raise UnboundLocalError even though x is defined globally?

    Assigning to x anywhere inside a function makes x local to the whole function. Reading it before the assignment then fails with UnboundLocalError. Declare global x, or pass x in as an argument, to fix it.

    IntermediateQuick answer1 min read