By Bonaventure Ogeto|

Python Interview Questions for Junior Developers

Python interviews for junior roles focus on core language mechanics: data types, list comprehensions, error handling, and basic OOP. Below are the questions that come up most often, each with a runnable answer and the reasoning behind it.

Questions on data types and mutability

Q: What is the difference between a list and a tuple?

A list is mutable (you can change, add, or remove items after creation). A tuple is immutable (once created, it cannot be changed). Use tuples for fixed collections like coordinates or database rows. Use lists when you need to modify the collection.

coords = (1.29, 36.82)   # Nairobi coordinates, will not change
scores = [85, 92, 78]     # student scores, might append more
scores.append(91)         # works
# coords.append(0.0)      # TypeError: tuple does not support append

Q: What is the difference between == and is?

== checks if two objects have the same value. is checks if they are the exact same object in memory.

a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)   # True  (same value)
print(a is b)   # False (different objects)

c = a
print(a is c)   # True  (same object)

Q: What are Python's main data types?

int, float, str, bool, list, tuple, dict, set, NoneType. Know when to use each. Dicts for key-value lookups. Sets for unique collections and fast membership tests.

Questions on list comprehensions and generators

Q: Rewrite this loop as a list comprehension.

# Loop version
result = []
for n in range(10):
    if n % 2 == 0:
        result.append(n ** 2)

# Comprehension version
result = [n ** 2 for n in range(10) if n % 2 == 0]
print(result)  # [0, 4, 16, 36, 64]

Q: What is a generator and why would you use one?

A generator produces values one at a time using yield instead of building the entire list in memory. Use generators when working with large datasets or infinite sequences.

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib = fibonacci()
for _ in range(10):
    print(next(fib), end=" ")  # 0 1 1 2 3 5 8 13 21 34

Questions on error handling

Q: How does try/except work?

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
except Exception as e:
    print(f"Unexpected error: {e}")
else:
    print(f"Result: {result}")  # runs only if no exception
finally:
    print("Always runs")        # cleanup code

Catch specific exceptions, not bare except:. Bare except catches everything including keyboard interrupts and system exits, which makes debugging harder.

Q: What is the difference between raise and assert?

raise throws an exception explicitly. assert is a debugging aid that throws AssertionError if a condition is False. Do not use assert for input validation in production because Python can be run with assertions disabled (python -O).

Questions on classes and OOP

Q: Explain __init__, self, and inheritance in Python.

class Animal:
    def __init__(self, name: str):
        self.name = name  # instance attribute

    def speak(self) -> str:
        return f"{self.name} makes a sound"

class Dog(Animal):  # inherits from Animal
    def speak(self) -> str:
        return f"{self.name} barks"

dog = Dog("Rex")
print(dog.speak())        # Rex barks
print(isinstance(dog, Animal))  # True

__init__ is the constructor, called when you create an instance. self refers to the instance being created or operated on. Inheritance lets a child class reuse and override the parent's methods.

Q: What are dunder methods?

Dunder (double underscore) methods like __str__, __repr__, __len__, __eq__ let you define how your objects behave with built-in operations. __str__ controls what print() shows. __len__ lets you use len() on your object.

Practical coding questions

Q: Reverse a string without using [::-1].

def reverse_string(s: str) -> str:
    result = ""
    for char in s:
        result = char + result
    return result

print(reverse_string("nairobi"))  # "iborian"

Q: Find the most frequent element in a list.

from collections import Counter

def most_frequent(items: list) -> any:
    counter = Counter(items)
    return counter.most_common(1)[0][0]

votes = ["yes", "no", "yes", "yes", "no"]
print(most_frequent(votes))  # "yes"

Q: Flatten a nested list.

def flatten(nested: list) -> list:
    result = []
    for item in nested:
        if isinstance(item, list):
            result.extend(flatten(item))
        else:
            result.append(item)
    return result

print(flatten([1, [2, [3, 4]], 5]))  # [1, 2, 3, 4, 5]

Frequently Asked Questions

How many questions should I expect in a Python interview?
Most junior interviews run 45 to 60 minutes with 3 to 5 coding questions and a few conceptual ones. Focus on getting the fundamentals right rather than memorising edge cases.
Should I learn Python 2 or Python 3 for interviews?
Python 3 only. Python 2 reached end of life in January 2020. No employer hiring today expects Python 2 knowledge from a junior candidate.
Do I need to know frameworks like Django or Flask for a Python interview?
Not always. Many junior interviews test core Python only. If the job posting mentions Django or Flask, prepare for those too, but core language knowledge comes first.

Ready to build real-world apps?

Join the McTaba Labs full-stack marathon. Ship 8 production apps with M-Pesa, USSD, and WhatsApp integrations, and get career support until placement.

See Programs