Interview Q&A / Python
Python interview questions
Lists, dictionaries, generators, decorators and the Python questions asked in service-company and data roles.
Prefer rapid revision? Practise Python short interview answers →
- 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 - 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