Python intermediate interview questions [Updated]

Python Intermediate Interview Questions

Deep Dive: Python Intermediate Interview Questions for Career Growth

Python intermediate interview questions are designed to test a candidate’s ability to apply Python concepts beyond the beginner level. If you’re preparing for technical interviews, it’s essential to practice not only basic syntax but also focus on python intermediate questions and python intermediate coding questions that evaluate your understanding of real-world problem solving and advanced language features.

Python is a general-purpose, dynamic, high-level, and interpreted programming language. It supports the object-oriented programming approach, which makes it a popular choice for developing robust applications. Its simple and readable syntax makes it easy to learn, yet its capabilities are powerful enough for enterprise-grade solutions.

Being an interpreted language, Python allows for rapid application development and scripting. Its dynamic typing and clean syntax make it ideal for beginners and professionals alike. However, in python intermediate interview questions, you’ll often encounter topics that go deeper—like decorators, list comprehensions, exception handling, and generators.

This versatility is reflected in the variety of python intermediate questions asked during interviews. You may be asked to build classes, implement interfaces, or manipulate data using functional techniques like map(), filter(), and lambda expressions.

One of the reasons Python stands out is its dynamic nature. You don’t need to specify data types explicitly. For example, simply writing a = 10 assigns an integer value to the variable without any type declaration. This flexibility speeds up development but also introduces challenges that are commonly addressed in python intermediate coding questions.

Python Intermediate Coding Questions

Python Intermediate Interview Questions
Python Intermediate Interview Questions

1. What are Python decorators?

Answer:
Decorators are a powerful tool in Python used to modify the behavior of a function or class. They are applied using the @decorator_name syntax above the function definition. Internally, a decorator is a higher-order function that takes a function as input and returns a new function with enhanced behavior.

def my_decorator(func):
def wrapper():
print("Before function execution")
func()
print("After function execution")
return wrapper

@my_decorator
def greet():
print("Hello!")

greet()

2. Explain list comprehension and its advantages.

Answer:
List comprehension provides a concise way to create lists in Python. It’s faster and more readable than traditional for-loops.

squares = [x*x for x in range(5)]
# Output: [0, 1, 4, 9, 16]

Advantages:

  • More compact code

  • Better performance

  • Easier to understand when used properly

3. What is the difference between is and == in Python?

Answer:

  • == checks value equality (whether the values are the same).

  • is checks identity (whether the two references point to the same object in memory).

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

4. What are Python generators?

Answer:
Generators are iterators created using functions and the yield keyword. They are memory-efficient and produce values one at a time.

def countdown(n):
while n > 0:
yield n
n -= 1

for i in countdown(5):
print(i)

5. Explain Python’s garbage collection.

Answer:
Python has an automated garbage collector that uses reference counting and cyclic garbage collection to free up unused memory.

  • Reference Count: If an object’s reference count drops to 0, it is garbage collected.

  • Cyclic GC: Detects and collects cycles of unreachable objects.

6. What is a lambda function in Python?

Answer:
Lambda functions are anonymous, single-expression functions defined using the lambda keyword.

square = lambda x: x*x
print(square(5)) # Output: 25

7. What are *args and kwargs?

Answer:

  • *args: Accepts variable number of positional arguments.

  • **kwargs: Accepts variable number of keyword arguments.

def demo(*args, **kwargs):
print(args)
print(kwargs)

demo(1, 2, 3, a=10, b=20)

8. What is the difference between a shallow copy and a deep copy?

Answer:

  • Shallow copy creates a new object but inserts references to the same objects.

  • Deep copy creates a new object and recursively copies all objects.

import copy
a = [[1, 2], [3, 4]]
shallow = copy.copy(a)
deep = copy.deepcopy(a)

9. How is exception handling done in Python?

Answer:
Using try, except, else, and finally blocks:

try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Always runs.")

10. What is a Python module and package?

Answer:

  • Module: A .py file with Python definitions and statements.

  • Package: A directory containing __init__.py file and multiple modules.

# mymodule.py
def hello():
print("Hello from module")

11. What is the difference between classmethod, staticmethod, and instance methods?

Answer:

  • @classmethod takes cls as the first argument and can access class variables.

  • @staticmethod doesn’t take self or cls and behaves like a normal function.

  • Instance methods take self and can access instance variables.

12. What is the purpose of __init__.py?

Answer:
It marks a directory as a Python package and allows imports from it. It can also run initialization code.

13. What is monkey patching in Python?

Answer:
Monkey patching is dynamically changing a class or module at runtime.

import math
math.sqrt = lambda x: 42
print(math.sqrt(9)) # Output: 42

14. What are Python’s magic methods?

Answer:
Magic methods (dunder methods) begin and end with double underscores, like __init__, __str__, __len__, etc., and define behavior of objects.

15. How do you handle files in Python?

Answer:
Using open(), read(), write(), and context managers:

with open('file.txt', 'r') as f:
content = f.read()

16. How do you manage memory in Python?

Answer:
Python handles memory with:

  • Reference counting

  • Automatic garbage collection

  • Memory pools (via PyMalloc)

17. What is the difference between @property and a method?

Answer:
@property allows a method to be accessed like an attribute.

class Circle:
def __init__(self, radius):
self._radius = radius

@property
def area(self):
return 3.14 * self._radius ** 2

18. What is a Python context manager?

Answer:
Used to manage resources (files, sockets) with with statement. Automatically handles __enter__ and __exit__.

19. Explain Python’s GIL (Global Interpreter Lock).

Answer:
GIL allows only one thread to execute Python bytecode at a time. It limits multithreading but is needed for memory safety.

20. How to use map, filter, and reduce?

Answer:

  • map() applies a function to all items.

  • filter() selects items based on a condition.

  • reduce() (from functools) applies cumulative function.

from functools import reduce
reduce(lambda x, y: x+y, [1,2,3]) # Output: 6

21. Difference between sort() and sorted()?

Answer:

  • sort() modifies the list in-place.

  • sorted() returns a new sorted list.

22. What is the purpose of enumerate()?

Answer:
Returns both index and item while iterating:

for i, v in enumerate(['a', 'b']):
print(i, v)

23. What are Python’s data classes?

Python’s data classes, introduced in Python 3.7 via PEP 557, are a decorator-based feature (@dataclass) designed to simplify the creation of classes that primarily store data. They automatically generate common methods like init, repr, eq, and others, reducing boilerplate code for classes that act as structured data containers.

24. What are Python sets and their features?

Python sets are unordered collections of unique, immutable elements. They are useful for operations involving membership testing, removing duplicates, and performing mathematical set operations.

Key Features of Python Sets:

  1. Unordered: Elements have no specific order, so indexing or slicing is not possible.
  2. Unique Elements: Duplicate elements are automatically removed.
  3. Mutable: Sets can be modified (add/remove elements), but the elements themselves must be immutable (e.g., numbers, strings, tuples).
  4. Dynamic: Sets can grow or shrink as elements are added or removed.
  5. No Indexing: Since sets are unordered, elements cannot be accessed via indices.
  6. Hashable Elements: Elements in a set must be hashable (i.e., they must have a valid __hash__ method).

25. Explain Python’s zip() function.

Python’s zip() function takes multiple iterables (like lists, tuples, or strings) and combines their elements into tuples, returning an iterator of these tuples. It pairs elements based on their position, stopping when the shortest iterable is exhausted.

a = [1, 2]
b = ['x', 'y']
list(zip(a, b)) # [(1, 'x'), (2, 'y')]

26. How to handle JSON in Python?

Answer:
Python provides the json module to parse and manipulate JSON data.

import json

# Convert dict to JSON string
data = {'name': 'John', 'age': 30}
json_str = json.dumps(data)

# Convert JSON string to dict
parsed = json.loads(json_str)

27. What are Python assertions?

Answer:
Assertions are used for debugging. The assert statement tests a condition and throws AssertionError if the condition is false.

x = 5
assert x > 0, "x must be positive"

28. What is the difference between del, remove(), and pop()?

Answer:

  • del removes by index or variable reference.

  • remove() deletes the first occurrence of a value.

  • pop() removes and returns the element at a given index.

lst = [1, 2, 3]
del lst[0]
lst.remove(2)
lst.pop(0)

29. Explain slicing with examples.

Answer:
Slicing extracts a portion of a list, tuple, or string: list[start:stop:step].

nums = [0, 1, 2, 3, 4, 5]
print(nums[1:4]) # [1, 2, 3]
print(nums[::-1]) # Reversed list

30. What is the difference between __str__() and __repr__()?

Answer:

  • __str__() is for user-friendly string representation.

  • __repr__() is for developers/debugging and should be unambiguous.

class Person:
def __repr__(self):
return "Person('John')"
def __str__(self):
return "John"

print(repr(Person()))
print(str(Person()))

31. What is a metaclass in Python?

Answer:
A metaclass is a class of a class. It defines how classes behave and are constructed. You can customize class creation using metaclasses.

class Meta(type):
def __new__(cls, name, bases, dct):
print("Creating class", name)
return super().__new__(cls, name, bases, dct)

class MyClass(metaclass=Meta):
pass

32. Explain type hinting.

Answer:
Type hinting allows you to specify the expected data types of function arguments and return values.

def greet(name: str) -> str:
return "Hello, " + name

It helps with code readability and tooling (e.g., static analysis with mypy).

33. What is duck typing?

Answer:
Duck typing focuses on behavior rather than the actual type. “If it walks like a duck and quacks like a duck, it’s a duck.”

def quack(duck):
duck.quack()

class Duck:
def quack(self):
print("Quack!")

quack(Duck()) # Works as long as the method exists

34. Explain the use of super().

Answer:
super() is used to call a method from a parent class in child classes, especially in multiple inheritance.

35. What are frozensets?

Answer:
frozenset is an immutable version of a set. It cannot be modified once created and is hashable (can be used as dict keys).

36. What is the use of globals() and locals()?

Answer:

  • globals() returns a dictionary of global scope.

  • locals() returns a dictionary of the current local symbol table.

x = 10
print(globals()['x'])

37. How do you use list and dictionary comprehensions?

Answer:
List and dictionary comprehensions provide a compact way to create collections.

squares = [x*x for x in range(5)]
even_dict = {x: x%2 == 0 for x in range(5)}

38. Explain try...except...else...finally.

Answer:

  • try: Run the code.

  • except: Handle exceptions.

  • else: Runs if no exception.

  • finally: Always runs.

try:
x = 10 / 2
except ZeroDivisionError:
print("Error")
else:
print("Success")
finally:
print("Done")

39. Are arguments passed by value or reference in Python?

Answer:
Python uses pass-by-object-reference. Mutable objects (like lists) can be changed, while immutable (like ints, strings) cannot.

def add(lst):
lst.append(5)

a = [1, 2]
add(a)
print(a) # [1, 2, 5]

40. Difference between iterator and iterable?

Answer:

  • Iterable: An object that can return an iterator (e.g., list, tuple).

  • Iterator: Object with __next__() and __iter__() methods.

nums = [1, 2, 3]
it = iter(nums)
print(next(it)) # 1

 

41. Explain multithreading vs multiprocessing in Python.

Answer:

  • Multithreading: Multiple threads within the same process; limited by the GIL.

  • Multiprocessing: Multiple processes with separate memory space; bypasses the GIL.

Use threading for I/O-bound and multiprocessing for CPU-bound tasks.

42. Explain Python’s logging module.

Python’s logging module provides a flexible framework for generating log messages in applications. It allows developers to track events, errors, and information during program execution, offering more control and configurability than print statements. Below is a comprehensive explanation of the logging module, its components, and how to use it effectively.

Key Components of the Logging Module:

  • Logger
  • Log Levels
  • Handler
  • Formatter
  • Filter

43. What is the yield from expression?

The yield from expression in Python is used in generator functions to delegate the generation of values to another iterable, such as a generator, list, or other iterable object. It simplifies the process of yielding values from a sub-iterable without needing to manually iterate over it.

Key Points about yield from:

  1. Purpose: It allows a generator to yield all values from another iterable (like a generator, list, or tuple) directly, as if they were yielded by the parent generator.
  2. Syntax: yield from <iterable>
  3. Introduced: Python 3.3 (PEP 380).
  4. Use Cases: It’s commonly used to chain generators, simplify code, and improve readability when working with nested iterables or sub-generators.

Mastering Python Intermediate Coding Questions: What to Expect and How to Prepare

python intermediate interview questions
Mastering Python Intermediate Coding Questions

Python Intermediate Coding Questions are designed to test not just your familiarity with syntax but also your ability to solve logical, algorithmic, and real-world programming challenges using Python’s powerful features.

Unlike basic questions (e.g., reversing a string or printing Fibonacci numbers), intermediate coding problems may involve:

🔹 Use of Data Structures

  • Manipulating nested lists or dictionaries
  • Using sets for performance optimization
  • Working with collections module (Counter, defaultdict, deque)

🔹 Working with Functional Programming

Python supports functional paradigms that are often tested in interviews through:

  • map(), filter(), reduce()
  • Lambda functions
  • List and dictionary comprehensions

🔹 File Handling and Exception Management

Many Python Intermediate Coding Questions include tasks such as:

  • Reading/writing files
  • Error handling with try-except
  • Logging or parsing structured data (like CSV, JSON)

🔹 Object-Oriented Design

OOP concepts such as:

  • Creating classes
  • Inheritance
  • Polymorphism
  • Use of @classmethod, @staticmethod, __str__, __repr__

These are common in python intermediate coding questions when you’re expected to write modular and reusable code.

🔹 Decorators and Generators

These more advanced features are often introduced at the intermediate level.

Common Python intermediate interview questions

Here’s what you can expect to be tested on:

  • String manipulation and pattern matching
  • Recursion vs. iteration
  • Custom sorting using key parameter
  • Working with dates and times
  • Dictionary flattening or merging
  • Data serialization (Pickle, JSON)
  • Multithreading & multiprocessing basics
  • Writing and testing custom modules

Benefits of Practicing Python Intermediate Interview Questions

If you’re aiming to land a job in software development, data science, or automation testing, mastering Python Intermediate Interview Questions offers several key benefits beyond just passing an interview. Here’s why dedicating time to these questions is a smart career move:

  • Bridges the Gap Between Beginner and Expert
  • Improves Problem-Solving and Coding Logic
  • Prepares You for Real Coding Rounds
  • Enhances Resume and Portfolio Quality
  • Builds Foundation for Advanced Concepts
  • Boosts Confidence for Tech Competitions and Hackathons
  • Makes You a Better Collaborator

✅ Final Thoughts on Python Intermediate Questions

Mastering python intermediate interview questions is essential for landing developer roles and excelling in coding interviews. If you’re serious about upgrading your skills, it’s the perfect time to enroll in a Python course that focuses on intermediate to advanced topics. A structured course can help you bridge the gap, build real-world projects, and prepare confidently for technical assessments.

Whether you’re aiming to switch careers, crack coding rounds, or simply level up your programming game—investing in a Python course is a smart move toward becoming a proficient Python developer.

Previous Article

Basic Python Interview Questions and Answers

Next Article

Experience Python Interview Questions and Answers

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Subscribe to our Newsletter

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨