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 →
- What does this function return when both try and finally have a return statement?
It returns the value from the finally block. finally always runs last, and a return inside it overrides the earlier return and even discards a pending exception. This is why returning from finally is considered bad practice.
AdvancedQuick answer1 min read - What does this print: a list of lambdas created in a loop, each returning i?
All the lambdas print the last value of i. Closures capture the variable, not its value at creation time, and i is looked up when the lambda is called. Fix it with a default argument: lambda i=i: i.
AdvancedQuick answer1 min read