Python Interview Questions

Python Interview Questions: Prepare for technical interviews with this comprehensive Python learning resource. Explore 48 structured modules covering Python fundamentals, variables, data types, functions, object-oriented programming, data structures, exception handling, debugging and practical coding challenges. Each module combines explanations, code examples and exercises to help beginners and aspiring Data Science professionals understand Python and develop problem-solving skills.

These Python Interview Questions are organised into progressive learning modules, helping you practise core concepts, understand code execution and prepare for technical interviews.

How to Prepare for Python Interview Questions

Interviewers assess more than whether code runs. For every answer, define the concept, state assumptions, trace a small example, mention failure modes, test an edge case and give time and space complexity where it applies. For Data Science questions, also discuss data leakage, reproducibility, dtypes, validation and the business meaning of a result.

  1. Beginner pass: modules 1–13; write small functions and explain values, names and control flow.
  2. Intermediate pass: modules 14–32; practise protocols, OOP, exceptions, packaging and copies.
  3. Advanced pass: modules 33–40; reason about concurrency, performance, testing and design.
  4. Data Science pass: modules 41–48; build a small, tested NumPy/pandas workflow and explain each transformation.

48 Python interview learning modules

1. Python introduction and execution model

Python source is compiled to bytecode and executed by an interpreter such as CPython. This model gives Python portability while keeping implementation details such as bytecode and reference counting relevant to performance discussions.

print("Hello, CampusCareer")

Execution and output: Output: Hello, CampusCareer. The interpreter parses the statement, creates bytecode and executes the call to print.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Python source is compiled to bytecode and executed by an interpreter such as CPython. This model gives Python portability while keeping implementation details such as bytecode and reference counting relevant to performance discussions.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: Hello, CampusCareer. The interpreter parses the statement, creates bytecode and executes the call to print.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: What is the difference between source code, bytecode and the Python virtual machine? A strong answer says source is human-readable Python, bytecode is an intermediate instruction format, and the virtual machine executes bytecode. The exact pipeline varies by implementation, so do not claim that every Python implementation uses CPython bytecode.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

2. Variables, identifiers and naming rules

A variable name is a reference to an object, not a labelled memory box containing a permanent type. Identifiers may contain letters, digits and underscores, cannot start with a digit, cannot be a keyword, and are case-sensitive.

student_count = 3nstudent_count += 1nprint(student_count)

Execution and output: Output: 4. Assignment binds the name, and augmented assignment evaluates the old value before rebinding it.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: A variable name is a reference to an object, not a labelled memory box containing a permanent type. Identifiers may contain letters, digits and underscores, cannot start with a digit, cannot be a keyword, and are case-sensitive.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: 4. Assignment binds the name, and augmented assignment evaluates the old value before rebinding it.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Why does x = 10 not declare an integer type? Python names are dynamically bound; the object has a type and the name can later refer to another object. Use descriptive snake_case names and avoid shadowing built-ins such as list.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

3. Built-in data types

Common built-ins include int, float, complex, bool, str, bytes, None, lists, tuples, sets and dictionaries. Choose a type based on the invariant your program needs, not only on syntax.

values = [42, 3.5, True, "data", None]nprint([type(value).__name__ for value in values])

Execution and output: Output: ['int', 'float', 'bool', 'str', 'NoneType']. bool is a distinct type but participates in numeric contexts.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Common built-ins include int, float, complex, bool, str, bytes, None, lists, tuples, sets and dictionaries. Choose a type based on the invariant your program needs, not only on syntax.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: ['int', 'float', 'bool', 'str', 'NoneType']. bool is a distinct type but participates in numeric contexts.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: How do is and == differ? == compares values using equality; is tests object identity. Use is None for the singleton and equality for ordinary values.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

4. Mutable versus immutable objects

Mutable objects can change in place; immutable objects cannot be changed after creation. Lists and dictionaries are mutable, while integers, strings and tuples are immutable. A tuple can still contain a mutable object, so immutability is about the tuple container itself.

items = [1, 2]nalias = itemsnalias.append(3)nprint(items)

Execution and output: Output: [1, 2, 3]. Both names reference the same list. This aliasing is a common interview trap.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Mutable objects can change in place; immutable objects cannot be changed after creation. Lists and dictionaries are mutable, while integers, strings and tuples are immutable. A tuple can still contain a mutable object, so immutability is about the tuple container itself.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: [1, 2, 3]. Both names reference the same list. This aliasing is a common interview trap.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Why can a tuple be a dictionary key but a list cannot? A key must have a stable hash. A tuple is hashable only when its elements are hashable; a list is mutable and unhashable. Copy mutable inputs when an API must own its data.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

5. Lists, tuples, sets and dictionaries

Lists preserve order and support indexed access; tuples represent fixed records; sets store unique hashable values; dictionaries map hashable keys to values. Python dictionaries preserve insertion order as a language guarantee in modern Python, but ordering should not replace explicit sorting when order matters semantically.

scores = {"Asha": 82, "Ravi": 76}nscores["Mina"] = 91nprint(sorted(scores.items(), key=lambda pair: pair[1], reverse=True))

Execution and output: Output: [('Mina', 91), ('Asha', 82), ('Ravi', 76)]. sorted returns a new list and the key function selects the score.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Lists preserve order and support indexed access; tuples represent fixed records; sets store unique hashable values; dictionaries map hashable keys to values. Python dictionaries preserve insertion order as a language guarantee in modern Python, but ordering should not replace explicit sorting when order matters semantically.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: [('Mina', 91), ('Asha', 82), ('Ravi', 76)]. sorted returns a new list and the key function selects the score.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Explain list versus set lookup. Indexing a list is typically O(1), membership is O(n); set membership is average O(1) because of hashing, with memory overhead and no index-based access.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

6. Operators and expressions

Expressions combine values with arithmetic, comparison, boolean, identity, membership and bitwise operators. Short-circuiting means and stops after a false operand and or stops after a true operand.

name = ""nlabel = name or "Anonymous"nprint(label)

Execution and output: Output: Anonymous. The empty string is falsy, so the right side is evaluated and returned.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Expressions combine values with arithmetic, comparison, boolean, identity, membership and bitwise operators. Short-circuiting means and stops after a false operand and or stops after a true operand.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: Anonymous. The empty string is falsy, so the right side is evaluated and returned.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Do not use is for numeric or string equality. Parenthesise mixed arithmetic and boolean expressions, and remember that and/or return operands rather than always returning booleans.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

7. Conditional statements

An if statement selects a branch based on truthiness. Use ordered conditions for mutually exclusive ranges and guard clauses for invalid inputs or early exits.

score = 78nif score >= 90:n    grade = "A"nelif score >= 60:n    grade = "Pass"nelse:n    grade = "Retry"nprint(grade)

Execution and output: Output: Pass. Python tests branches from top to bottom and executes only the first matching branch.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: An if statement selects a branch based on truthiness. Use ordered conditions for mutually exclusive ranges and guard clauses for invalid inputs or early exits.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: Pass. Python tests branches from top to bottom and executes only the first matching branch.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: A frequent error is using separate if statements when only one branch should run. Test boundaries such as 59, 60, 89 and 90, not just a typical value.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

8. Loops and loop control

Use for to iterate over an iterable and while when repetition depends on a changing condition. break exits the loop, continue skips the current iteration, and a loop else runs only if no break occurred.

for number in range(5):n    if number == 3:n        breakn    print(number)

Execution and output: Output is 0, 1, 2 on separate lines. range(5) stops before 5 and the break prevents 3 from printing.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Use for to iterate over an iterable and while when repetition depends on a changing condition. break exits the loop, continue skips the current iteration, and a loop else runs only if no break occurred.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output is 0, 1, 2 on separate lines. range(5) stops before 5 and the break prevents 3 from printing.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Avoid modifying a list while iterating over it. Iterate over a copy or build a new list. For an infinite while loop, identify the state change that eventually makes the condition false.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

9. Functions and arguments

Functions package a named operation and create a local scope. A good function has a clear contract: inputs, output, side effects, errors and complexity. Prefer returning values over printing inside reusable logic.

def average(values):n    if not values:n        raise ValueError("values cannot be empty")n    return sum(values) / len(values)nnprint(average([2, 4, 6]))

Execution and output: Output: 4.0. The guard rejects an undefined empty average; the return value can be tested or reused.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Functions package a named operation and create a local scope. A good function has a clear contract: inputs, output, side effects, errors and complexity. Prefer returning values over printing inside reusable logic.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: 4.0. The guard rejects an undefined empty average; the return value can be tested or reused.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: What is the difference between a parameter and an argument? A parameter is the name in the function definition; an argument is the value supplied at the call site. Explain validation and exceptions as part of the function contract.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

10. Positional, keyword, default and variable-length arguments

Positional arguments match by order, keyword arguments match by name, defaults fill omitted values, *args collects extra positional arguments and **kwargs collects extra keyword arguments. Put keyword-only parameters after * when clarity matters.

def connect(host, port=5432, *, timeout=5):n    return f"{host}:{port} timeout={timeout}"nnprint(connect("db.local", timeout=10))

Execution and output: Output: db.local:5432 timeout=10. The keyword-only timeout is explicit and the default port is retained.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Positional arguments match by order, keyword arguments match by name, defaults fill omitted values, *args collects extra positional arguments and **kwargs collects extra keyword arguments. Put keyword-only parameters after * when clarity matters.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: db.local:5432 timeout=10. The keyword-only timeout is explicit and the default port is retained.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Why is a mutable default dangerous? A default is evaluated once at function definition time. Use None and create the list inside the function. Also avoid accepting arbitrary arguments when a precise signature communicates the API better.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

11. Scope, LEGB rule and namespaces

Python resolves a name using Local, Enclosing, Global and Built-in scopes. A namespace maps names to objects. global and nonlocal can rebind outer names, but passing values and returning results is usually clearer.

message = "global"ndef show():n    message = "local"n    return messagenprint(show(), message)

Execution and output: Output: local global. The local binding shadows the global one only inside the function.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Python resolves a name using Local, Enclosing, Global and Built-in scopes. A namespace maps names to objects. global and nonlocal can rebind outer names, but passing values and returning results is usually clearer.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: local global. The local binding shadows the global one only inside the function.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Explain why assigning to a name anywhere in a function makes it local unless declared otherwise. A read before that assignment raises UnboundLocalError. Prefer dependency injection over hidden global state.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

12. Lambda functions

A lambda is a small anonymous function containing one expression. It is useful for a short key or callback, not for multi-step business logic where a named function and docstring improve readability.

names = ["Mina", "alex", "Ravi"]nprint(sorted(names, key=lambda name: name.lower()))

Execution and output: Output: ['alex', 'Mina', 'Ravi']. Sorting uses the lowercase value while preserving original spelling.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: A lambda is a small anonymous function containing one expression. It is useful for a short key or callback, not for multi-step business logic where a named function and docstring improve readability.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: ['alex', 'Mina', 'Ravi']. Sorting uses the lowercase value while preserving original spelling.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Can a lambda contain statements? No; it contains an expression. In interviews, mention that a named function is preferable when the transformation needs tests, a meaningful name or more than one operation.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

13. List, dictionary and set comprehensions

Comprehensions express a transformation and optional filter. They create a new container and should remain readable; nested comprehensions can hide expensive work and logic errors.

squares = [number * number for number in range(6) if number % 2 == 0]nlookup = {number: number * number for number in range(3)}nprint(squares, lookup)

Execution and output: Output: [0, 4, 16] {0: 0, 1: 1, 2: 4}. The filter runs before the expression is added.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Comprehensions express a transformation and optional filter. They create a new container and should remain readable; nested comprehensions can hide expensive work and logic errors.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: [0, 4, 16] {0: 0, 1: 1, 2: 4}. The filter runs before the expression is added.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: A comprehension is not automatically faster or better. Use a generator expression for a one-pass large input, and avoid variable leakage assumptions from older Python versions.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

14. Iterators and iterables

An iterable can produce an iterator; an iterator implements __iter__ and __next__ and remembers its position. Lists are reusable iterables, while an iterator is usually consumed once.

values = iter([10, 20])nprint(next(values))nprint(next(values))

Execution and output: Output: 10 then 20. A further next raises StopIteration, which a for loop handles internally.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: An iterable can produce an iterator; an iterator implements __iter__ and __next__ and remembers its position. Lists are reusable iterables, while an iterator is usually consumed once.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: 10 then 20. A further next raises StopIteration, which a for loop handles internally.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Why does iter(list) differ from the list? The list stores all values and can be iterated repeatedly; the iterator is the stateful traversal object. This distinction matters for memory and one-shot streams.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

15. Generators and yield

A generator function pauses at yield and resumes later, providing lazy evaluation and low memory usage. It is ideal for files, pipelines and large sequences when all values need not exist simultaneously.

def countdown(start):n    while start:n        yield startn        start -= 1nnprint(list(countdown(3)))

Execution and output: Output: [3, 2, 1]. Calling the function creates a generator; execution begins when it is iterated.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: A generator function pauses at yield and resumes later, providing lazy evaluation and low memory usage. It is ideal for files, pipelines and large sequences when all values need not exist simultaneously.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: [3, 2, 1]. Calling the function creates a generator; execution begins when it is iterated.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: What is the cost of a generator? It usually stores only execution state, so space is O(1) besides yielded values, but it is one-pass and may be slower if repeated materialisation is required.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

16. Decorators

A decorator receives a callable and returns a callable, commonly to add logging, timing, validation or authorisation without editing the wrapped function. Preserve metadata with functools.wraps.

from functools import wrapsnndef announce(function):n    @wraps(function)n    def wrapper(*args, **kwargs):n        print("calling", function.__name__)n        return function(*args, **kwargs)n    return wrappernn@announcendef add(a, b):n    return a + bnnprint(add(2, 3))

Execution and output: Output: calling add followed by 5. Decoration happens when the function is defined; the wrapper runs when it is called.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: A decorator receives a callable and returns a callable, commonly to add logging, timing, validation or authorisation without editing the wrapped function. Preserve metadata with functools.wraps.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: calling add followed by 5. Decoration happens when the function is defined; the wrapper runs when it is called.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Explain closure capture, wrapper forwarding and metadata preservation. A common error is forgetting to return the wrapped result or failing to support keyword arguments.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

17. Closures

A closure is an inner function that remembers values from its enclosing scope after the outer function returns. Use nonlocal when the inner function must rebind the captured name.

def make_counter():n    count = 0n    def next_count():n        nonlocal countn        count += 1n        return countn    return next_countnncounter = make_counter()nprint(counter(), counter())

Execution and output: Output: 1 2. The returned function retains the enclosing count cell.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: A closure is an inner function that remembers values from its enclosing scope after the outer function returns. Use nonlocal when the inner function must rebind the captured name.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: 1 2. The returned function retains the enclosing count cell.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Explain late binding in loops: closures capture the variable, not a snapshot. Use a default argument or a factory when each callback needs its own value.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

18. Recursion

Recursion solves a problem by reducing it to smaller instances and requires a base case plus progress toward it. Python limits recursion depth, so iteration is often safer for deep input.

def factorial(number):n    if number < 0:n        raise ValueError("negative input")n    if number in (0, 1):n        return 1n    return number * factorial(number - 1)nnprint(factorial(5))

Execution and output: Output: 120. Calls descend to the base case and then return while multiplying each pending frame.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Recursion solves a problem by reducing it to smaller instances and requires a base case plus progress toward it. Python limits recursion depth, so iteration is often safer for deep input.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: 120. Calls descend to the base case and then return while multiplying each pending frame.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: State time and space complexity: factorial is O(n) time and O(n) call-stack space. Naive recursive Fibonacci is exponential; memoisation or iteration changes the cost.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

19. Object-oriented programming

OOP models state and behaviour together, but it is not mandatory for every problem. Use classes when an object has a coherent invariant or lifecycle; use functions and composition when they are simpler.

class Temperature:n    def __init__(self, celsius):n        self.celsius = celsiusn    def fahrenheit(self):n        return self.celsius * 9 / 5 + 32nnprint(Temperature(25).fahrenheit())

Execution and output: Output: 77.0. The instance stores Celsius and the method derives Fahrenheit.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: OOP models state and behaviour together, but it is not mandatory for every problem. Use classes when an object has a coherent invariant or lifecycle; use functions and composition when they are simpler.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: 77.0. The instance stores Celsius and the method derives Fahrenheit.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: When is composition better than inheritance? When a class needs a collaborator rather than an “is-a” relationship. Composition reduces coupling and makes dependencies easier to replace in tests.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

20. Classes and objects

A class is a blueprint and an object is an instance with identity, attributes and behaviour. Instance attributes usually belong to one object; class attributes are shared by the class unless shadowed.

class Student:n    school = "CampusCareer"n    def __init__(self, name):n        self.name = namennfirst = Student("Asha")nprint(first.name, first.school)

Execution and output: Output: Asha CampusCareer. Attribute lookup finds the instance name and then the class attribute.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: A class is a blueprint and an object is an instance with identity, attributes and behaviour. Instance attributes usually belong to one object; class attributes are shared by the class unless shadowed.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: Asha CampusCareer. Attribute lookup finds the instance name and then the class attribute.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Avoid mutable class attributes for per-instance state. Put self.courses = [] in the constructor, not on the class, unless shared state is intentional.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

21. Constructors and self

Python calls __init__ after creating an instance; technically __new__ creates it. self is the conventional explicit reference to the current instance and is passed automatically when an instance method is called.

class Account:n    def __init__(self, owner, balance=0):n        self.owner = ownern        self.balance = balancennaccount = Account("Ravi", 100)nprint(account.owner, account.balance)

Execution and output: Output: Ravi 100. Account(...) constructs an object and invokes __init__ with the instance as self.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Python calls __init__ after creating an instance; technically __new__ creates it. self is the conventional explicit reference to the current instance and is passed automatically when an instance method is called.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: Ravi 100. Account(...) constructs an object and invokes __init__ with the instance as self.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: The constructor should establish valid invariants. Validate inputs early and do not confuse self with a keyword; it is a convention, although using another name would still bind the first parameter.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

22. Inheritance and method resolution order

Inheritance reuses and specialises behaviour. Python uses C3 method resolution order (MRO) to determine where attribute lookup proceeds, especially in multiple inheritance. Inspect it with Class.mro().

class Parent:n    def label(self):n        return "parent"nclass Child(Parent):n    passnprint(Child().label(), Child.mro())

Execution and output: Output begins with parent and the MRO includes Child, Parent, object. Use super() for cooperative parent calls.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Inheritance reuses and specialises behaviour. Python uses C3 method resolution order (MRO) to determine where attribute lookup proceeds, especially in multiple inheritance. Inspect it with Class.mro().
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output begins with parent and the MRO includes Child, Parent, object. Use super() for cooperative parent calls.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Do not say Python always calls the nearest textual parent. Explain MRO and cooperative multiple inheritance, and test diamond hierarchies rather than guessing.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

23. Polymorphism

Polymorphism means code can use different objects through a shared behaviour, often by duck typing. Python cares about supported operations rather than a declared interface in many situations.

def total_area(shapes):n    return sum(shape.area() for shape in shapes)nnclass Square:n    def __init__(self, side): self.side = siden    def area(self): return self.side ** 2nnprint(total_area([Square(3)]))

Execution and output: Output: 9. The function only requires an area method.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Polymorphism means code can use different objects through a shared behaviour, often by duck typing. Python cares about supported operations rather than a declared interface in many situations.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: 9. The function only requires an area method.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: What is duck typing? If an object supports the required protocol, it can be used. Keep the protocol small and make failures clear; static typing with Protocol can document it without forcing inheritance.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

24. Encapsulation and abstraction

Python uses conventions such as _name for internal implementation and name mangling for __name; it does not enforce private fields like some languages. Abstraction exposes a useful contract while hiding implementation details.

class BankAccount:n    def __init__(self):n        self._balance = 0n    def deposit(self, amount):n        if amount <= 0: raise ValueError("amount must be positive")n        self._balance += amountn    @propertyn    def balance(self): return self._balancennaccount = BankAccount()naccount.deposit(50)nprint(account.balance)

Execution and output: Output: 50. The property exposes read access while keeping mutation behind validation.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Python uses conventions such as _name for internal implementation and name mangling for __name; it does not enforce private fields like some languages. Abstraction exposes a useful contract while hiding implementation details.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: 50. The property exposes read access while keeping mutation behind validation.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Encapsulation is about protecting invariants, not hiding every attribute. Prefer a small public API and explain that leading underscores communicate intent rather than provide security.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

25. Method overloading and overriding in Python

Python does not support signature-based method overloading in the same way as Java; a later definition replaces an earlier one. Use defaults, keyword-only parameters, *args or functools.singledispatch when appropriate. Overriding means a subclass supplies a compatible implementation.

class Formatter:n    def format(self, value, prefix=""):n        return prefix + str(value)nnprint(Formatter().format(7, "ID: "))

Execution and output: Output: ID: 7. One flexible method replaces multiple overloads.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Python does not support signature-based method overloading in the same way as Java; a later definition replaces an earlier one. Use defaults, keyword-only parameters, *args or functools.singledispatch when appropriate. Overriding means a subclass supplies a compatible implementation.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: ID: 7. One flexible method replaces multiple overloads.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Distinguish overriding from overloading. An override should preserve the parent contract, including accepted inputs and meaningful return behaviour; violating substitutability creates fragile code.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

26. Static methods, class methods and instance methods

Instance methods receive self, class methods receive cls and are useful alternate constructors, and static methods receive neither automatically. Choose the narrowest binding that communicates dependencies.

class User:n    def __init__(self, name): self.name = namen    @classmethodn    def from_email(cls, email): return cls(email.split("@")[0])n    @staticmethodn    def valid_email(email): return "@" in emailnnprint(User.from_email("[email protected]").name, User.valid_email("x@y"))

Execution and output: Output: asha True. The class method constructs through the class, while the static method is a namespaced utility.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Instance methods receive self, class methods receive cls and are useful alternate constructors, and static methods receive neither automatically. Choose the narrowest binding that communicates dependencies.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: asha True. The class method constructs through the class, while the static method is a namespaced utility.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: A class method supports inheritance because it uses cls; hard-coding the class name in an alternate constructor can create the wrong subtype.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

27. Exception handling and custom exceptions

Exceptions separate error detection from recovery. Catch the narrowest expected exception, use else for code that should run only after success, finally for cleanup, and custom exceptions for domain-specific failures.

class InvalidScoreError(ValueError):n    passnndef validate(score):n    if not 0 <= score <= 100:n        raise InvalidScoreError("score must be between 0 and 100")n    return scorenntry:n    validate(120)nexcept InvalidScoreError as error:n    print(error)

Execution and output: Output: score must be between 0 and 100. The specific exception is caught without hiding unrelated programming errors.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Exceptions separate error detection from recovery. Catch the narrowest expected exception, use else for code that should run only after success, finally for cleanup, and custom exceptions for domain-specific failures.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: score must be between 0 and 100. The specific exception is caught without hiding unrelated programming errors.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Never use a bare except: in ordinary application code. Do not silently return a success-shaped value after an error. Preserve context with raise NewError(...) from error when translating exceptions.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

28. File handling

Use open with an explicit encoding and a context manager so the file closes even if reading fails. Choose text or binary mode deliberately and validate external data.

from io import StringIOnnwith StringIO("AshanRavin") as file:n    names = [line.strip() for line in file if line.strip()]nprint(names)

Execution and output: Output: ['Asha', 'Ravi']. The comprehension streams lines and removes whitespace.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Use open with an explicit encoding and a context manager so the file closes even if reading fails. Choose text or binary mode deliberately and validate external data.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: ['Asha', 'Ravi']. The comprehension streams lines and removes whitespace.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: For a real file use open(path, encoding="utf-8"). Avoid loading huge files with read() when iteration is sufficient. Handle missing files specifically and test permissions and malformed records.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

29. Context managers and with statements

A context manager defines setup and cleanup through __enter__ and __exit__, or through contextlib.contextmanager. The with statement guarantees cleanup and can optionally suppress an exception when __exit__ returns true.

from contextlib import contextmanagernn@contextmanagerndef labelled(name):n    print("open", name)n    try:n        yield namen    finally:n        print("close", name)nnwith labelled("resource") as value:n    print(value)

Execution and output: Output is open resource, resource, then close resource. Cleanup runs even when the body raises.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: A context manager defines setup and cleanup through __enter__ and __exit__, or through contextlib.contextmanager. The with statement guarantees cleanup and can optionally suppress an exception when __exit__ returns true.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output is open resource, resource, then close resource. Cleanup runs even when the body raises.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Explain why with is safer than manually calling close. A custom context manager must not accidentally suppress errors; return False or None unless suppression is intentional.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

30. Modules, packages and imports

A module is a Python file; a package groups modules and may expose a public API. Imports execute module top-level code once per interpreter process and bind names in the importing namespace.

from math import hypotnprint(hypot(3, 4))

Execution and output: Output: 5.0. Import only the name needed when that improves clarity; use module-qualified names when provenance matters.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: A module is a Python file; a package groups modules and may expose a public API. Imports execute module top-level code once per interpreter process and bind names in the importing namespace.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: 5.0. Import only the name needed when that improves clarity; use module-qualified names when provenance matters.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Avoid circular imports by moving shared contracts to a lower-level module, importing locally only as a deliberate last resort, and keeping top-level side effects behind if __name__ == "__main__":.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

31. pip and virtual environments

A virtual environment isolates project dependencies from the system interpreter. Create one with python -m venv .venv, activate it, install with python -m pip install package, and record reproducible requirements.

python -m venv .venvnpython -m pip install requestsnpython -m pip freeze > requirements.txt

Execution and output: These are shell commands, not Python statements. The environment keeps the project’s packages separate and python -m pip targets the selected interpreter.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: A virtual environment isolates project dependencies from the system interpreter. Create one with python -m venv .venv, activate it, install with python -m pip install package, and record reproducible requirements.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: These are shell commands, not Python statements. The environment keeps the project’s packages separate and python -m pip targets the selected interpreter.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Why can pip install into the wrong place? Multiple Python installations may have different pip executables. Check python -m pip --version, pin compatible versions and never commit the environment directory.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

32. Shallow copy versus deep copy

A shallow copy creates a new outer container but keeps references to nested objects; a deep copy recursively copies nested objects. Prefer explicit constructors or immutable values when copy semantics matter.

import copynoriginal = [[1], [2]]nshallow = copy.copy(original)ndeep = copy.deepcopy(original)noriginal[0].append(9)nprint(shallow, deep)

Execution and output: Output: [[1, 9], [2]] [[1], [2]]. The shallow copy shares inner lists; the deep copy does not.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: A shallow copy creates a new outer container but keeps references to nested objects; a deep copy recursively copies nested objects. Prefer explicit constructors or immutable values when copy semantics matter.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: [[1, 9], [2]] [[1], [2]]. The shallow copy shares inner lists; the deep copy does not.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Do not blindly deep-copy objects containing files, locks or external resources. Explain ownership and use targeted copies for predictable performance.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

33. Memory management and garbage collection

CPython primarily tracks references and immediately deallocates objects whose reference count reaches zero; cyclic garbage is handled by the cyclic garbage collector. Implementation details are not language guarantees across all Python implementations.

import sysnvalue = []nalias = valuenprint(sys.getrefcount(value) >= 2)

Execution and output: Output is True; the exact count is implementation- and temporary-reference-dependent, so do not rely on it for application logic.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: CPython primarily tracks references and immediately deallocates objects whose reference count reaches zero; cyclic garbage is handled by the cyclic garbage collector. Implementation details are not language guarantees across all Python implementations.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output is True; the exact count is implementation- and temporary-reference-dependent, so do not rely on it for application logic.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Memory leaks can still occur through long-lived references, caches, global containers or cycles involving finalizers. Profile allocations and release ownership rather than calling gc.collect() as a generic fix.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

34. Python GIL and concurrency concepts

In standard CPython builds, the Global Interpreter Lock allows one thread at a time to execute Python bytecode in a process. It does not make all programs thread-safe and does not prevent concurrency during I/O or in extension code that releases the lock.

import threadingncounter = 0nlock = threading.Lock()nndef increment():n    global countern    for _ in range(1000):n        with lock:n            counter += 1nnthreads = [threading.Thread(target=increment) for _ in range(2)]nfor thread in threads: thread.start()nfor thread in threads: thread.join()nprint(counter)

Execution and output: Output: 2000. The lock makes the read-modify-write operation safe.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: In standard CPython builds, the Global Interpreter Lock allows one thread at a time to execute Python bytecode in a process. It does not make all programs thread-safe and does not prevent concurrency during I/O or in extension code that releases the lock.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: 2000. The lock makes the read-modify-write operation safe.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Avoid saying “the GIL makes race conditions impossible.” Shared mutable state still needs synchronisation. For CPU-bound work consider processes or native/vectorised code; for I/O-bound work threads or async can overlap waits.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

35. Multithreading, multiprocessing and asynchronous programming

Threads share memory and suit blocking I/O; processes have separate memory and can use multiple CPU cores; async tasks cooperatively interleave at await points and suit many non-blocking I/O operations. Choose based on workload and library support.

import asyncionnasync def greet():n    await asyncio.sleep(0)n    return "ready"nnprint(asyncio.run(greet()))

Execution and output: Output: ready. The event loop resumes the coroutine after its awaitable completes.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Threads share memory and suit blocking I/O; processes have separate memory and can use multiple CPU cores; async tasks cooperatively interleave at await points and suit many non-blocking I/O operations. Choose based on workload and library support.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: ready. The event loop resumes the coroutine after its awaitable completes.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Do not call blocking code directly in an async event loop. Explain process serialisation costs, thread coordination, cancellation and backpressure. Benchmark a representative workload instead of assuming concurrency improves it.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

36. Regular expressions

Regular expressions describe text patterns. Use raw strings for patterns, named groups for maintainability, anchors when the whole string must match, and compiled patterns when reused.

import renmatch = re.fullmatch(r"(?P<year>d{4})-(?P<month>d{2})", "2026-11")nprint(match.groupdict())

Execution and output: Output: {'year': '2026', 'month': '11'}. fullmatch rejects extra characters.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Regular expressions describe text patterns. Use raw strings for patterns, named groups for maintainability, anchors when the whole string must match, and compiled patterns when reused.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: {'year': '2026', 'month': '11'}. fullmatch rejects extra characters.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Regex is not always the right parser. Avoid catastrophic backtracking, validate untrusted input carefully, and use re.escape for literal user-provided fragments.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

37. Working with JSON and APIs

JSON maps naturally to Python dictionaries, lists, strings, numbers, booleans and null. API code must handle status codes, timeouts, authentication, rate limits, schema changes and untrusted input.

import jsonnpayload = json.loads('{"name": "Asha", "active": true}')nprint(payload["name"], payload["active"])

Execution and output: Output: Asha True. loads parses text; load reads a file. Use a timeout and validate required fields for real HTTP requests.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: JSON maps naturally to Python dictionaries, lists, strings, numbers, booleans and null. API code must handle status codes, timeouts, authentication, rate limits, schema changes and untrusted input.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: Asha True. loads parses text; load reads a file. Use a timeout and validate required fields for real HTTP requests.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Never assume every response is JSON or successful. Check the status, catch a narrow decoding/network error, log safe context and avoid printing tokens or personal data.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

38. Testing, debugging and logging

Tests specify expected behaviour; debugging isolates the smallest failing case; logging records useful runtime facts at appropriate levels. Prefer deterministic unit tests and add integration tests at boundaries.

import loggingnlogging.basicConfig(level=logging.INFO)nndef double(value):n    result = value * 2n    logging.info("computed result=%s", result)n    return resultnnprint(double(4))

Execution and output: Output includes an INFO log followed by 8 (the exact log prefix depends on configuration). Logging uses placeholders rather than eager string formatting.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Tests specify expected behaviour; debugging isolates the smallest failing case; logging records useful runtime facts at appropriate levels. Prefer deterministic unit tests and add integration tests at boundaries.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output includes an INFO log followed by 8 (the exact log prefix depends on configuration). Logging uses placeholders rather than eager string formatting.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Do not test implementation details unnecessarily. Reproduce the bug, inspect values and stack traces, make one change, then rerun the smallest test. Never log secrets, passwords or full sensitive payloads.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

39. Time and space complexity of common operations

Complexity describes growth as input size increases. List append is amortised O(1), indexed access O(1), list membership O(n), dictionary and set membership average O(1), sorting O(n log n), and copying n items O(n). State assumptions and worst-case caveats.

values = [4, 1, 3]nordered = sorted(values)nprint(ordered)

Execution and output: Output: [1, 3, 4]. Sorting allocates a new list, so it costs O(n) extra space in addition to the O(n log n) comparison work.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Complexity describes growth as input size increases. List append is amortised O(1), indexed access O(1), list membership O(n), dictionary and set membership average O(1), sorting O(n log n), and copying n items O(n). State assumptions and worst-case caveats.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: [1, 3, 4]. Sorting allocates a new list, so it costs O(n) extra space in addition to the O(n log n) comparison work.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: A common mistake is calling every dictionary operation O(1) without saying average-case hashing assumptions. Include input size, auxiliary space and whether output space is counted.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

40. Python best practices and PEP 8

Readable Python uses meaningful names, small cohesive functions, four-space indentation, consistent imports, docstrings for public APIs and explicit error handling. PEP 8 is a style guide; tools such as formatters and linters automate consistency but do not replace design judgment.

def percentage(part: float, whole: float) -> float:n    """Return part as a percentage of whole."""n    if whole == 0:n        raise ValueError("whole cannot be zero")n    return part / whole * 100nnprint(percentage(1, 4))

Execution and output: Output: 25.0. The annotation and docstring communicate the contract; validation prevents division by zero.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Readable Python uses meaningful names, small cohesive functions, four-space indentation, consistent imports, docstrings for public APIs and explicit error handling. PEP 8 is a style guide; tools such as formatters and linters automate consistency but do not replace design judgment.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: 25.0. The annotation and docstring communicate the contract; validation prevents division by zero.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Discuss readability, cohesion, tests, dependency management and backwards compatibility. Avoid premature abstraction, wildcard imports, unexplained globals and broad exception catches.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

41. NumPy arrays and broadcasting

NumPy arrays store homogeneous values efficiently and support vectorised operations. Broadcasting aligns compatible dimensions without manually repeating values; incompatible shapes raise an error.

import numpy as npnvalues = np.array([1, 2, 3])nprint(values * 2)nprint(values + np.array([10]))

Execution and output: Output: [2 4 6] and [11 12 13]. The scalar and one-element array broadcast across the three elements.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: NumPy arrays store homogeneous values efficiently and support vectorised operations. Broadcasting aligns compatible dimensions without manually repeating values; incompatible shapes raise an error.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: [2 4 6] and [11 12 13]. The scalar and one-element array broadcast across the three elements.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Do not confuse a NumPy view with a copy. Inspect shape, dtype and memory sharing when modifying slices. Broadcasting must be explained dimension by dimension.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

42. pandas Series and DataFrames

A Series is a labelled one-dimensional array; a DataFrame is a labelled two-dimensional table made from aligned Series. Inspect shape, dtypes, head and describe before analysis.

import pandas as pdndata = pd.DataFrame({"team": ["A", "B"], "score": [80, 90]})nprint(data["score"].mean())

Execution and output: Output: 85.0. Selecting one column returns a Series and mean aggregates its numeric values.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: A Series is a labelled one-dimensional array; a DataFrame is a labelled two-dimensional table made from aligned Series. Inspect shape, dtypes, head and describe before analysis.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: 85.0. Selecting one column returns a Series and mean aggregates its numeric values.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Avoid chained assignment and ambiguous index meaning. Use .loc for label-based selection, document whether indexes are meaningful, and preserve dtypes through cleaning.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

43. Indexing, filtering and groupby

Use boolean masks for filtering, .loc for labels and conditions, .iloc for integer positions, and groupby to split, apply aggregation and combine results.

import pandas as pdndata = pd.DataFrame({"team": ["A", "A", "B"], "score": [80, 90, 70]})nprint(data.loc[data["score"] >= 80].groupby("team")["score"].mean())

Execution and output: Output shows team A with mean 85.0. Filtering occurs before grouping, so team B is excluded.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Use boolean masks for filtering, .loc for labels and conditions, .iloc for integer positions, and groupby to split, apply aggregation and combine results.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output shows team A with mean 85.0. Filtering occurs before grouping, so team B is excluded.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Parenthesise combined masks and use &/|, not Python and/or, because a Series contains many truth values. Check the row count after every filter and join.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

44. Missing-value handling

Missingness may mean unknown, not applicable or a data collection failure. Inspect missingness, decide whether to drop, impute or model it, and record the choice. Never fill blindly with zero.

import pandas as pdndata = pd.DataFrame({"score": [80, None, 90]})ndata["score"] = data["score"].fillna(data["score"].median())nprint(data["score"].tolist())

Execution and output: Output: [80.0, 85.0, 90.0]. The median is computed from observed values and used for the missing row.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Missingness may mean unknown, not applicable or a data collection failure. Inspect missingness, decide whether to drop, impute or model it, and record the choice. Never fill blindly with zero.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: [80.0, 85.0, 90.0]. The median is computed from observed values and used for the missing row.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Fit imputation values on training data only to prevent leakage. Distinguish NaN, None and empty strings, and test whether a missingness indicator carries meaning.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

45. Merging, joining and concatenating

Concatenation stacks compatible tables; merging matches rows using keys. Choose one-to-one, one-to-many or many-to-many validation, select join type deliberately, and inspect unmatched rows and row counts.

import pandas as pdnleft = pd.DataFrame({"id": [1, 2], "name": ["A", "B"]})nright = pd.DataFrame({"id": [2, 3], "score": [90, 70]})nprint(left.merge(right, on="id", how="left"))

Execution and output: The result keeps ids 1 and 2; id 1 has a missing score and id 3 is excluded. A left join preserves the left table’s grain.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Concatenation stacks compatible tables; merging matches rows using keys. Choose one-to-one, one-to-many or many-to-many validation, select join type deliberately, and inspect unmatched rows and row counts.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: The result keeps ids 1 and 2; id 1 has a missing score and id 3 is excluded. A left join preserves the left table’s grain.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Duplicate keys can multiply rows unexpectedly. Check uniqueness before merging, use validate="one_to_one" when appropriate, and compare before/after row counts.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

46. Vectorization

Vectorization applies array or Series operations in compiled loops instead of Python-level row iteration. It is often faster and clearer, but correctness, memory and readability still matter.

import pandas as pdndata = pd.DataFrame({"price": [10, 20], "quantity": [2, 3]})ndata["total"] = data["price"] * data["quantity"]nprint(data["total"].tolist())

Execution and output: Output: [20, 60]. The column expression operates elementwise without iterrows.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Vectorization applies array or Series operations in compiled loops instead of Python-level row iteration. It is often faster and clearer, but correctness, memory and readability still matter.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output: [20, 60]. The column expression operates elementwise without iterrows.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Do not vectorize blindly when a clear group operation or custom function is required. Avoid apply as a first resort, benchmark alternatives and verify dtype and missing-value behaviour.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

47. Data cleaning and preprocessing

Cleaning is a documented pipeline: define the target grain, standardise names and types, remove or justify duplicates, validate ranges, handle missingness, encode categories and split data before fitting transformations.

import pandas as pdndata = pd.DataFrame({"age": ["20", "21"], "city": [" Delhi ", "Delhi"]})ndata["age"] = pd.to_numeric(data["age"], errors="raise")ndata["city"] = data["city"].str.strip().str.lower()nprint(data.to_dict("records"))

Execution and output: Output is records with integer ages and the normalised city delhi. Each transformation is explicit and testable.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: Cleaning is a documented pipeline: define the target grain, standardise names and types, remove or justify duplicates, validate ranges, handle missingness, encode categories and split data before fitting transformations.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: Output is records with integer ages and the normalised city delhi. Each transformation is explicit and testable.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: A clean-looking dataset can still contain leakage, incorrect units or duplicated entities. Keep raw data unchanged, log decisions, write validation checks and fit learned transformations only on training data.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

48. Matplotlib and visualization basics

A useful chart answers a question with appropriate encodings, labels, units and honest scales. Separate data preparation from plotting and make figures reproducible with explicit titles, axes and legends.

import matplotlib.pyplot as pltnmonths = ["Jan", "Feb", "Mar"]nvalues = [10, 14, 12]nfig, ax = plt.subplots()nax.plot(months, values, marker="o")nax.set(title="Monthly values", xlabel="Month", ylabel="Count")nfig.tight_layout()

Execution and output: The code creates a line chart; it does not need to print text. The axes communicate the dimensions and tight_layout reduces overlap.

Interview questions by level

  • Beginner: Explain the purpose of this concept and name one correct use. Answer: A useful chart answers a question with appropriate encodings, labels, units and honest scales. Separate data preparation from plotting and make figures reproducible with explicit titles, axes and legends.
  • Intermediate: Trace the example and state its output or observable behaviour. Answer: The code creates a line chart; it does not need to print text. The axes communicate the dimensions and tight_layout reduces overlap.
  • Advanced: Discuss a trade-off, edge case, implementation detail or complexity concern. Answer: Do not use a line chart for unordered categories, truncate an axis to exaggerate differences, or omit units. Explain why the chart matches the question and inspect outliers before interpreting a pattern.

Practice: change the input, test an empty or invalid case, and write one assertion for the expected behaviour. Common mistake: giving a definition without stating an assumption, edge case or complexity.

Output-prediction questions

Predict without running the code, then verify in a Python 3.11+ interpreter and explain every line.

  1. items = [1, 2]nalias = itemsnalias += [3]nprint(items is alias, items)

    Answer: True [1, 2, 3]; augmented list concatenation mutates the same list.

  2. def add(value, bucket=[]):n    bucket.append(value)n    return bucketnprint(add(1))nprint(add(2))

    Answer: [1] then [1, 2]; the default list is shared. Fix it with bucket=None.

  3. print([x * 2 for x in range(4) if x % 2])

    Answer: [2, 6]; only odd values 1 and 3 pass the truth test.

  4. data = {"a": 1}nprint(data.get("b", 0), "b" in data)

    Answer: 0 False; get avoids a KeyError and membership checks keys.

  5. def outer():n    value = 10n    def inner():n        return value + 1n    return innernprint(outer()())

    Answer: 11; the closure retains the enclosing value.

Debugging lab

Use a failing input, read the traceback from the bottom upward, inspect types and intermediate values, then make the smallest correction. Do not “fix” an exception by catching everything.

  1. Wrong result: average = sum(values) / len(values) - 1. Write a test for [2, 4], inspect operator precedence, and remove the unintended subtraction.
  2. KeyError: replace row["email"] only if the field is genuinely optional; otherwise validate the input and report the missing required field.
  3. Shared state: reproduce a mutable-default bug with two calls, then use a None sentinel and a fresh list.
  4. Pandas warning: create an explicit copy after filtering and assign with .loc; assert the expected row count and dtypes.
  5. Slow loop: measure a nested membership search, replace repeated list membership with a set where order is not required, and compare complexity.

Practical coding challenges with solutions

For each challenge, first state the contract and edge cases, then implement and test.

  1. First unique character: count characters with a dictionary, then scan in order. Solution: two passes, O(n) time and O(k) space.
  2. Balanced brackets: push opening symbols onto a list and match closing symbols. Solution: stack, O(n) time and O(n) space.
  3. Group records: build a dictionary from department to records. Solution: groups.setdefault(department, []).append(record).
  4. Merge intervals: sort by start, then merge when the next start overlaps the current end. Solution: O(n log n) time from sorting.
  5. Top words: normalise text, count with Counter, and call most_common; define tie behaviour.
  6. CSV quality report: stream rows, validate required columns, count invalid records and write a summary. Do not load an unbounded file into memory.
  7. Retry decorator: write a decorator that retries a specific exception a bounded number of times, preserves metadata and re-raises the final error.
  8. Async gather: run independent simulated I/O tasks concurrently, measure elapsed time and explain cancellation and exception propagation.
  9. DataFrame pipeline: load data, normalise columns, validate keys, impute using training statistics, group by category and plot one clearly labelled result.
  10. Interview mini-project: build a command-line study tracker with modules, a virtual environment, JSON persistence, tests, logging and a README explaining complexity.

FAQs and final revision checklist

Should I memorise every Python method?

No. Know the core protocols, read documentation quickly, and explain why a method fits the data structure. Interviewers value reasoning, tests and trade-offs more than memorised trivia.

What version should I use?

Use a maintained Python 3 release supported by your employer or course, pin project dependencies, and avoid relying on implementation-specific behaviour unless you identify it explicitly.

How should I prepare for Data Science interviews?

Combine Python language fundamentals with SQL, statistics and a reproducible pandas/NumPy project. Explain data quality, leakage, evaluation, visualisation choices and limitations rather than only showing a model score.

  • Can I explain names, identity, equality, mutability and hashability?
  • Can I write functions with safe defaults and precise exceptions?
  • Can I trace an iterator, generator, decorator and closure?
  • Can I explain OOP trade-offs, MRO and method binding?
  • Can I choose threads, processes or async from workload characteristics?
  • Can I state average and worst-case complexity for common operations?
  • Can I write a test before debugging and log without leaking secrets?
  • Can I inspect pandas shape, dtypes, missingness and row counts after each transformation?
  • Can I explain joins, duplicate keys, leakage and vectorisation?
  • Can I communicate assumptions, edge cases, output and a simpler alternative?

References: Python tutorial, execution model, itertools, asyncio, copy, PEP 8, NumPy broadcasting, pandas guide, Matplotlib pyplot. Continue with the Data Science roadmap, SQL interview guide and Programming Fundamentals course.