Practice questions and answer explanations
Try an answer before reading the explanation. These are practice examples; adapt them to your own experience and expect different questions in an actual interview.
Why can a mutable default argument cause a Python bug?
Default argument values are evaluated when the function is defined, rather than recreated for each call. If a function appends to a default list, later calls can see values from earlier calls. Use None as the default and create a new list inside the function when the argument is None. Explain when sharing state is intentional and when each caller should receive an independent collection.
Try this next: How would you demonstrate the bug with two calls that omit the list argument?
What is the difference between == and is in Python?
The == operator compares values according to the objects’ equality behavior. The is operator checks whether both references point to the same object. Two separately created lists can contain equal values without being the same list. Use is None for a None check. Do not rely on integer or string interning to compare values, since object reuse is not the value comparison contract.
Try this next: If a and b refer to different lists containing [1, 2], what do a == b and a is b return?
When would you use a generator instead of a list?
A generator produces values as they are requested, so it can process a stream without storing every result at once. A list stores its elements and supports indexed access and repeated iteration. A generator is consumed as you iterate over it; a second pass requires recreating it or storing the results. Discuss whether the caller needs random access, multiple passes, or only one sequential scan before choosing.
Try this next: How would your design change if a large-file processing pipeline needs to revisit every parsed record twice?
How would you remove duplicates while preserving order?
For hashable values, keep a set of values already seen and an output list. Scan the input once, appending a value only on its first appearance. This takes expected O(n) time and O(n) extra space, assuming constant-time hashing and equality. A plain set does not express the required output order. For dictionaries or other unhashable items, first define which stable key determines whether two items are duplicates.
Try this next: For records with userId and timestamp fields, should two records with the same userId count as duplicates? Clarify before coding.