Python Interview Questions and Answers

Reason about Python behaviour with small examples, then explain the edge cases your code must handle.

Python interviews often test whether you can reason about objects, functions and iteration. Run small examples, predict their output and explain the edge cases. Clear, tested code is more useful than memorising language trivia.

Objects and collections

1. How do lists and tuples differ?

A list supports changes to its elements; a tuple does not support replacing its elements. A tuple can still contain a mutable object, such as a list. Choose based on the meaning of the data and the operations needed, not a blanket claim that tuples are always faster.

2. How do == and is differ?

Equality compares values according to the objects' comparison behaviour. Identity asks whether two references point to the same object. Use 'is None' for the None singleton, and use equality when comparing ordinary values such as strings or numbers.

3. When would you use a dictionary or a set?

A dictionary maps keys to values; a set represents distinct values. Both require hashable keys or elements. Use a dictionary for lookup by identifier and a set for membership or deduplication when order is not the requirement.

4. What is a shallow copy?

A shallow copy creates a new outer container while keeping references to nested objects. Mutating a shared nested list can therefore affect both containers. Decide which objects must be independent rather than assuming every copy recursively duplicates all data.

Sources: Python tutorial: data structures. Checked 23 October 2026.

Functions and arguments

5. Why can a mutable default argument cause a bug?

Default argument objects are created when the function is defined, not once per call. If the function changes a default list, later calls can observe earlier changes. Use None as a sentinel and create a fresh list inside the function when that is the intended behaviour.

6. What do *args and **kwargs collect?

They collect additional positional arguments into a tuple and additional keyword arguments into a dictionary. Use them when an API needs that flexibility. Explicit parameters usually make a small function's contract easier to understand and validate.

7. What is a closure?

A nested function can retain access to names from an enclosing scope. Be careful when creating functions in a loop: the captured name may be looked up later, after its value changes. Bind the intended value explicitly when each function needs a separate snapshot.

def add_tag(tag, tags=None):
    result = [] if tags is None else list(tags)
    result.append(tag)
    return result

assert add_tag('python') == ['python']
assert add_tag('ml') == ['ml']
original = ['data']
assert add_tag('ml', original) == ['data', 'ml']
assert original == ['data']

Sources: Python tutorial: functions and control flow. Checked 23 October 2026.

Iteration and class behaviour

8. How is a generator different from a list?

A generator produces values as it is iterated and retains execution state between yields. A list stores its elements for repeated access. A generator can reduce retained memory, but it may be exhausted and its work happens during iteration rather than at construction.

9. What is the difference between an iterable and an iterator?

An iterable can provide an iterator. An iterator supplies successive values and signals completion with StopIteration. A list can produce multiple independent iterators; a single iterator generally moves forward as it is consumed.

10. Why should per-instance mutable state be created on the instance?

A mutable class attribute is shared through the class unless an instance shadows it. Put a list that belongs to each object in its initialisation method. Otherwise, adding an item through one instance can unexpectedly change what another instance sees.

Sources: Python tutorial: classes, iterators and generators. Checked 23 October 2026.

A small coding exercise

Write a function that counts non-empty labels after trimming whitespace. State whether matching is case-sensitive, whether inputs must be strings and how invalid input should behave. Those choices belong to the function contract; the interviewer should not have to infer them.

This example expects strings and treats uppercase and lowercase as different labels. Test an empty input, whitespace-only labels and repeated labels. For a single pass through n labels, discuss the work of processing the strings as well as dictionary operations; avoid describing every input as constant-time.

def count_labels(labels):
    counts = {}
    for label in labels:
        key = label.strip()
        if key:
            counts[key] = counts.get(key, 0) + 1
    return counts

assert count_labels([' AI ', '', 'AI', 'ML']) == {'AI': 2, 'ML': 1}
assert count_labels([]) == {}

Common questions

Which Python version do these examples target?

The examples use ordinary Python 3 features and no external packages. Confirm the Python version used by an employer before preparing version-specific features.

How should I answer when I do not know an output?

Explain your assumptions, reduce the code to a small example and reason through it. If you can run it, compare the result with your prediction and explain what you learned.

Explore AI training

Bring Us the Problem. We Will Help Define the Right Build.

Tell us what users need to do, what is slowing the business down and what a successful outcome should look like. We will help you identify the appropriate AI, software, product or training pathway.