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