🧠 Advanced Python Interview Questions and Answers for Freshers (Part 2)
Once you have a basic understanding of Python, interviewers often test how well you understand deeper concepts such as object-oriented programming, memory management, file handling, and built-in modules.
In this part, you’ll find advanced Python interview questions and answers written in easy, beginner-friendly language but with professional depth — perfect for freshers who want to stand out.
1. What is object-oriented programming (OOP) in Python?
Answer:
Object-Oriented Programming (OOP) is a way of writing code using classes and objects.
It allows data and functions to be grouped together, making programs easier to understand and reuse.
Example:
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(self.name + " says Woof!")
dog1 = Dog("Tommy")
dog1.bark()
Explanation:
Here, Dog is a class, and dog1 is an object. The method bark() belongs to the class.
2. What are the four main principles of OOP?
Answer:
- Encapsulation: Hiding internal details of a class.
- Abstraction: Showing only essential information to the user.
- Inheritance: Reusing code by deriving one class from another.
- Polymorphism: Using one function name for different purposes.
3. What are Python class methods and static methods?
Answer:
- Instance method: Works with object data (most common).
- Class method: Works with class data, defined using
@classmethod. - Static method: Doesn’t need access to class or object data, defined using
@staticmethod.
Example:
class Student:
school = "ABC School"
@classmethod
def get_school(cls):
return cls.school
@staticmethod
def greet():
print("Welcome to ABC School")
print(Student.get_school())
Student.greet()
4. What are Python generators?
Answer:
Generators are functions that yield values one at a time instead of returning all values at once.
They are memory-efficient for large data.
Example:
def countdown(n):
while n > 0:
yield n
n -= 1
for number in countdown(5):
print(number)
Explanation:
The yield keyword pauses the function and remembers its state, which helps save memory.
5. What is a Python iterator?
Answer:
An iterator is an object that allows you to loop through elements one by one using next().
Example:
numbers = [1, 2, 3]
it = iter(numbers)
print(next(it)) # 1
print(next(it)) # 2
6. What is the difference between @staticmethod, @classmethod, and instance methods?
| Method Type | Access | Decorator Used | Example Use |
|---|---|---|---|
| Instance Method | Object | None | Works with self |
| Class Method | Class | @classmethod | Access class variables |
| Static Method | None | @staticmethod | General utility function |
7. What are Python namespaces?
Answer:
A namespace is a container that holds variable names and their values.
It helps avoid naming conflicts in large programs.
Types:
- Local Namespace – inside a function
- Global Namespace – top-level of the script
- Built-in Namespace – Python’s predefined names
8. What is the difference between shallow and deep copy in Python?
Answer:
A shallow copy copies only references (not actual objects).
A deep copy creates a full independent copy.
Example:
import copy
a = [[1, 2], [3, 4]]
b = copy.copy(a)
c = copy.deepcopy(a)
9. What are Python decorators used for?
Answer:
Decorators modify the behavior of a function or class without changing its actual code.
They are often used for logging, authentication, or performance measurement.
Example:
def log(func):
def wrapper():
print("Function started")
func()
print("Function ended")
return wrapper
@log
def greet():
print("Hello")
greet()
10. What are Python comprehensions?
Answer:
Comprehensions allow you to create lists, sets, or dictionaries in a single line.
Examples:
# List comprehension
squares = [x*x for x in range(5)]
# Dictionary comprehension
nums = {x: x*x for x in range(3)}
11. What is the difference between deep and shallow equality in Python?
Answer:
- Shallow equality (
==) checks if values are equal. - Deep equality (
is) checks if both point to the same object in memory.
12. What is Python’s garbage collection?
Answer:
Python automatically cleans up unused memory using garbage collection.
It removes objects that are no longer referenced in the program.
13. What are Python closures?
Answer:
A closure is a function inside another function that remembers variables from the outer function even after it’s finished executing.
Example:
def outer_func(x):
def inner_func(y):
return x + y
return inner_func
add5 = outer_func(5)
print(add5(10)) # Output: 15
14. What are Python’s data structures?
Answer:
Python has several built-in data structures:
- List: Ordered, mutable
- Tuple: Ordered, immutable
- Set: Unordered, no duplicates
- Dictionary: Key-value pairs
15. What is file handling in Python?
Answer:
File handling lets you read, write, and append files using the open() function.
Example:
with open("sample.txt", "w") as f:
f.write("Hello, world!")
16. What are exceptions in Python?
Answer:
Exceptions are runtime errors.
They are handled using try, except, else, and finally.
Example:
try:
num = int(input("Enter a number: "))
except ValueError:
print("That’s not a number!")
else:
print("Number entered:", num)
17. How can you manage memory in Python?
Answer:
Python handles memory automatically using:
- Reference counting
- Garbage collector You can also manually delete objects using
del.
18. What are Python’s built-in functions?
Answer:
Common built-in functions include: len(), type(), id(), sorted(), sum(), min(), max(), range(), print().
19. What is the difference between mutable and immutable objects?
Answer:
- Mutable: Can be changed (e.g., list, dictionary, set).
- Immutable: Cannot be changed (e.g., tuple, string, int).
Example:
name = "John"
# name[0] = "M" → Error (immutable)
20. What is multithreading in Python?
Answer:
Multithreading allows multiple parts of a program to run at the same time.
It improves performance but is limited by the Global Interpreter Lock (GIL).
Example:
import threading
def task():
print("Running in thread")
t1 = threading.Thread(target=task)
t1.start()
21. What is the Global Interpreter Lock (GIL)?
Answer:
GIL is a mechanism in Python that allows only one thread to execute at a time in the interpreter.
It prevents memory corruption but limits true parallelism in multi-core systems.
22. What is the difference between deepcopy() and copy()?
Answer:
copy()→ Shallow copy (references only top-level objects).deepcopy()→ Makes a full copy of all nested objects.
23. What are Python’s popular frameworks?
Answer:
- Django – Web development
- Flask – Lightweight web framework
- Pandas – Data analysis
- NumPy – Numerical computing
- TensorFlow / PyTorch – Machine learning
24. What are Python iterables and iterators?
Answer:
- Iterable: Any object you can loop over (
list,tuple, etc.). - Iterator: An object that produces elements one at a time using
next().
25. What are docstrings in Python?
Answer:
Docstrings are used to document functions, classes, or modules.
They’re written using triple quotes """ ... """.
Example:
def add(a, b):
"""This function adds two numbers."""
return a + b
26. What is the difference between remove(), pop(), and del in lists?
| Method | Description | Example |
|---|---|---|
remove(x) | Removes first occurrence of x | list.remove(2) |
pop(i) | Removes element at index i | list.pop(0) |
del | Deletes element or entire list | del list[1] |
27. What is the difference between JSON and Pickle in Python?
Answer:
- JSON: Used to store and exchange data in text format.
- Pickle: Used to serialize and deserialize Python objects (binary format).
Example:
import pickle
data = {"name": "John"}
with open("data.pkl", "wb") as f:
pickle.dump(data, f)
28. What is the with statement used for?
Answer:
The with statement simplifies resource management like file handling.
It automatically closes the file after use.
Example:
with open("file.txt") as f:
data = f.read()
29. What is Python’s __str__() method?
Answer:__str__() defines how an object is represented as a string.
Example:
class Student:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Student name: {self.name}"
print(Student("Moutusi"))
30. What is the difference between is and == in Python?
Answer:
is→ checks if two variables refer to the same object.==→ checks if the values are equal.
✅ Conclusion
Understanding these advanced Python concepts will not only prepare you for interviews but also help you write cleaner and more efficient code. Interviewers often test both theory and coding practice — so keep coding regularly and try small projects to strengthen your knowledge.