Python interview questions, with answers you can run

Python interviews mix a few coding warm-ups with questions about how the language behaves. These are the ones that come up most. Each example below was run, and the output shown is exact, so you can rely on it when you explain it out loud.

Reverse a string

Slicing with a step of -1 walks the string backwards. It works on any sequence, including lists.

print("python"[::-1])

Output:

nohtyp

Does a list contain duplicates?

A set keeps each value once. If the set is shorter than the list, something was repeated. State the cost out loud: this is a single pass, and items must be hashable.

numbers = [1, 2, 3, 2, 1]
print(len(numbers) != len(set(numbers)))

Output:

True

Are two words anagrams?

Two words are anagrams when their sorted letters are equal.

print(sorted("listen") == sorted("silent"))

Output:

True

Lists versus tuples

Lists can change after they are created, tuples cannot. Tuples are used for fixed groups such as a point, and because they cannot change they can be dictionary keys.

point = (3, 4)
try:
    point[0] = 9
except TypeError:
    print("tuples cannot change")

Output:

tuples cannot change

is versus ==

== asks whether two values are equal. is asks whether they are the very same object in memory. Two separate lists with the same content are equal but not the same.

a = [1, 2]
b = [1, 2]
print(a == b)
print(a is b)

Output:

True
False

The mutable default argument trap

A default value is created once, when the function is defined, not on every call. With a list as the default, every call shares the same list. This is the most famous Python gotcha.

def add_item(item, items=[]):
    items.append(item)
    return items

print(add_item("a"))
print(add_item("b"))

Output:

['a']
['a', 'b']

The fix: use None

Use None as the default and create the list inside the function. Now each call starts fresh.

def add_item(item, items=None):
    if items is None:
        items = []
    items.append(item)
    return items

print(add_item("a"))
print(add_item("b"))

Output:

['a']
['b']

Common questions

What Python topics do interviews cover most?
Strings, lists, dictionaries and sets for the coding warm-up, then functions, errors, classes and how mutable and immutable types behave. Know the cost of the common operations and explain your choice of data structure.
Should I memorise solutions?
Understand the idea behind each one instead. If you can explain why a set finds duplicates in one pass, you can solve the next variation you have never seen.
How do I practise explaining my answer?
Run each example, then say out loud what it prints and why before you look at the explanation. Interviewers care about your reasoning as much as the code.

Practise it