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. Write a class that implements the iterator protocol to count down from n to 1.

    Define __iter__ returning self and __next__ returning the next value, raising StopIteration when the countdown ends. Store the current position on the instance. Each next call is O(1) and the class uses O(1) space.

    IntermediateQuick answerCoding1 min read
  2. 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