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. How do dictionary and set comprehensions work in Python?

    A dict comprehension uses curly braces with key: value, as in {k: v for ...}. A set comprehension uses curly braces with one expression, as in {x for ...}, and removes duplicates automatically.

    BeginnerQuick answer1 min read
  2. In a list comprehension, where does the if go: before or after the for?

    A filter if goes after the for clause and drops items. An if-else that chooses between two values is an expression, so it goes before the for. Writing else after the for is a SyntaxError.

    BeginnerQuick answer1 min read
  3. What is a list comprehension in Python, and when should you use one?

    A list comprehension builds a list in one expression: [expr for item in iterable if condition]. It is shorter and usually faster than an append loop. Use it for simple transform-and-filter work, not for complicated logic.

    BeginnerQuick answer1 min read
  4. Write a function to flatten a list of lists into a single list.

    For one level of nesting, use a nested comprehension: [x for row in rows for x in row]. For arbitrary depth, use recursion and check isinstance(item, list). The flat version is O(n) in the number of elements.

    BeginnerQuick answerCoding1 min read
  5. 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
  6. Write a function to transpose a matrix (swap its rows and columns).

    Use zip(*matrix) and convert each tuple to a list, or use a nested comprehension indexing matrix[r][c]. The first row becomes the first column. The time is O(rows x cols).

    IntermediateQuick answerCoding1 min read