Top 100 Advanced Python Questions and
Answers
Structured Q&A Format
Introduction
Python is a versatile language used in advanced fields like AI, data science, and
automation. Below are 100 advanced questions and answers, formatted for clarity to
help you prepare for interviews or deepen your Python understanding.
Advanced Python Questions and Answers
Question: What is the difference between deep copy and shallow copy in Python?
Answer: A shallow copy creates a new object but does not create copies of nested
objects; instead, it references them. A deep copy creates copies of all nested objects.
Use copy.copy() for a shallow copy and copy.deepcopy() for a deep copy.
Question: Explain Python's Global Interpreter Lock (GIL). How does it affect
multithreading?
Answer: The GIL allows only one thread to execute Python bytecode at a time, limiting
true parallelism in multi-threaded Python programs. It affects CPU-bound operations
but not I/O-bound tasks.
Question: What are decorators in Python? Provide an example.
Answer: Decorators are functions that modify the functionality of another function.
Example:
def my_decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
Question: How does list comprehension differ from generator expression?
Answer: List comprehensions return a list immediately. Generator expressions return an
iterator that yields items on demand.
Question: Describe how you would implement a singleton pattern in Python.
Answer: Override the __new__ method:
class Singleton:
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super().__new__(cls)
return cls._instance
Question: What is the difference between @staticmethod and @classmethod?
Answer: @staticmethod does not take self or cls as parameters and does not access
class or instance variables. @classmethod takes cls as its first parameter and can
access/modify class state.
Question: Explain the use of the 'with' statement and context managers in Python.
Answer: The with statement simplifies exception handling by encapsulating common
preparation and cleanup tasks. Objects that support it implement __enter__ and
__exit__ methods.
with open('file.txt') as f:
data = f.read()
Question: How do you handle memory leaks in Python?
Answer: Memory leaks can occur due to lingering references, cycles, or
mismanagement of resources. Use gc module for garbage collection and context
managers to release resources.
Question: What is monkey patching in Python?
Answer: Monkey patching is modifying or extending code at runtime without altering the
original source code, often for testing or hotfixes. Use with caution.
Question: How do you use the 'yield' keyword?
Answer: yield turns a function into a generator, allowing lazy evaluation and iteration
over potentially large datasets.
def count_up(n):
for i in range(n):
yield i
Question: What is metaclass in Python?
Answer: A metaclass is a class of a class that defines how a class behaves. Typically,
type is the default metaclass, but you can define custom metaclasses by inheriting from
type.
Question: Explain method resolution order (MRO) in Python.
Answer: MRO determines the order in which Python looks for a method in a hierarchy of
classes. Python uses the C3 linearization algorithm.
Question: What is the purpose of __slots__ in Python classes?
Answer: __slots__ restricts the allowed attributes and saves memory by preventing the
creation of __dict__ for each instance.
Question: How does Python’s garbage collection work?
Answer: Python uses reference counting and cyclic garbage collection to manage
memory automatically.
Question: Explain the difference between bytes and bytearray in Python.
Answer: bytes is immutable while bytearray is mutable. Both represent sequences of
bytes.
Question: What is the difference between ‘is’ and ‘==’ in Python?
Answer: is checks for object identity, == checks for value equality.
Question: How can you implement multithreading and multiprocessing in Python?
Answer: Use the threading module for multithreading and multiprocessing module for
true parallelism.
Question: What are magic methods in Python? Give examples.
Answer: Magic methods are special methods with double underscores (e.g., __init__,
__str__, __add__) that enable operator overloading and object customization.
Question: What is the difference between xrange and range in Python 2 and Python 3?
Answer: In Python 2, range returns a list and xrange returns an iterator. In Python 3, only
range exists and behaves like xrange.
Question: Explain duck typing in Python with an example.
Answer: Duck typing is based on an object’s methods/properties rather than its type. If it
walks like a duck and quacks like a duck, treat it as a duck.
Question: How do you create an abstract class in Python?
Answer: Use the abc module with @abstractmethod decorator to define abstract
methods.
from abc import ABC, abstractmethod
class MyABC(ABC):
@abstractmethod
def do_something(self):
pass
Question: What is the purpose of the super() function?
Answer: super() calls a method from the parent/base class, useful in multiple
inheritance and method overriding.
Question: How do you handle exceptions in Python?
Answer: Use try-except blocks, optionally adding else and finally clauses for handling
other scenarios.
Question: What are *args and **kwargs?
Answer: *args collects additional positional arguments; **kwargs collects additional
keyword arguments.
Question: What does the @property decorator do?
Answer: It makes a method act like an attribute, allowing encapsulation and validation.
Question: Explain the difference between __init__ and __new__.
Answer: __new__ creates an instance, __init__ initializes it. __new__ is usually used for
immutable objects.
Question: What are frozen sets in Python?
Answer: A frozenset is an immutable set.
Question: How do you merge two dictionaries in Python 3.5+?
Answer: merged = {**dict1, **dict2}
Question: What is the difference between sorted() and list.sort()?
Answer: sorted() returns a new sorted list; list.sort() sorts the list in place and returns
None.
Question: How do you use lambda functions?
Answer: lambda creates anonymous functions:
add = lambda x, y: x + y
Question: Explain the purpose of the pass, continue, and break statements.
Answer: pass does nothing, continue skips to the next iteration, break exits the loop.
Question: What is the difference between a module and a package?
Answer: A module is a single Python file. A package is a collection of modules in a
directory with an __init__.py file.
Question: How do you use the zip() function?
Answer: zip() combines multiple iterables into tuples.
Question: How can you make a class iterable?
Answer: Implement __iter__ and __next__ methods.
Question: What is a coroutine in Python?
Answer: Coroutines are functions that can pause and resume their execution using yield
or await.
Question: Describe how to handle circular imports.
Answer: Restructure code, import inside functions, or use import statements at the end
of the module.
Question: What is the difference between hasattr() and getattr()?
Answer: hasattr() checks if an object has an attribute; getattr() retrieves the attribute
value.
Question: What is asyncio and how is it used?
Answer: asyncio is a library for writing concurrent code using async/await syntax, mainly
for I/O-bound and high-level structured network code.
Question: Explain the difference between threading.Lock and threading.RLock.
Answer: Lock is a basic mutex; RLock is a reentrant lock that can be acquired multiple
times by the same thread.
Question: How do you serialize objects in Python?
Answer: Use the pickle module for generic Python objects or json for interoperable
objects.
Question: How do you implement caching in Python?
Answer: Use functools.lru_cache decorator or third-party libraries like cachetools.
Question: What is the GIL and why does it exist?
Answer: The Global Interpreter Lock (GIL) ensures that only one thread runs Python
code at a time, simplifying memory management but limiting parallelism.
Question: How can you enforce data hiding in Python?
Answer: Use name mangling with double underscores (e.g., __var) or underscore prefix
to indicate private members.
Question: What are context variables in Python?
Answer: contextvars is a module for managing, storing, and accessing context-local
state, especially useful in async code.
Question: How do you create a custom iterator?
Answer: Implement __iter__() and __next__() methods in your class.
Question: What is the purpose of __call__ in a class?
Answer: Allows an instance to be called as a function.
Question: What is the difference between set and list?
Answer: A set is unordered and unique, while a list is ordered and can have duplicates.
Question: How do you reverse a string in Python?
Answer: reversed_string = my_string[::-1]
Question: What does the enumerate() function do?
Answer: Returns an iterator of tuples containing (index, value) pairs from an iterable.
Question: How do you chain function decorators?
Answer: Stack decorators using multiple @ lines above a function.
Question: What is the difference between a shallow copy and assignment?
Answer: Assignment copies the reference; a shallow copy copies the object but not
nested objects.
Question: How to measure execution time of Python code?
Answer: Use time.time(), timeit module, or datetime module.
Question: How do you handle command-line arguments?
Answer: Use sys.argv or argparse module.
Question: What are type hints (annotations) in Python?
Answer: Syntax to indicate the expected data type of function arguments and return
values, improving code readability and tooling.
Question: How do you create and use virtual environments in Python?
Answer: Use python -m venv venv_name to create and activate a virtual environment to
manage dependencies.
Question: What is the difference between __str__ and __repr__?
Answer: __str__ is for user-friendly string representation, __repr__ is for unambiguous
representation for developers.
Question: What does the walrus operator := do?
Answer: Assigns values to variables as part of an expression (introduced in Python 3.8).
Question: What are namespaces in Python?
Answer: Namespaces are mappings from names to objects, implemented as
dictionaries, which help avoid name collisions.
Question: How do you perform unit testing in Python?
Answer: Use the unittest or pytest frameworks.
Question: How do you handle Unicode in Python?
Answer: Use u'string' or ensure strings are encoded/decoded properly.
Question: What is the difference between map(), filter(), and reduce()?
Answer: map() applies a function to all items; filter() filters items; reduce() applies a
rolling computation to items, needs functools import.
Question: Explain the difference between an iterator and an iterable.
Answer: An iterable is an object you can iterate over; an iterator is the object that does
the actual iteration with __next__().
Question: How do you use list comprehension with conditionals?
Answer: [x for x in iterable if condition]
Question: How can you read/write JSON files in Python?
Answer: Use the json module's load() and dump() functions.
Question: What is the difference between class variable and instance variable?
Answer: Class variables are shared; instance variables are unique to each instance.
Question: How do you use super() in multiple inheritance?
Answer: super() calls the next method in the MRO, useful for cooperative multiple
inheritance.
Question: How can you avoid race conditions in threading?
Answer: Using locks, semaphores, or other synchronization primitives.
Question: What are property setters and deleters?
Answer: They allow controlling write/delete access to attributes using @property.setter
and @property.deleter.
Question: How do you create a custom exception?
Answer: Subclass Exception and define custom behavior.
Question: What is the difference between os.path and pathlib?
Answer: os.path works with string paths; pathlib provides object-oriented filesystem
paths (Python 3.4+).
Question: How do you use regular expressions in Python?
Answer: Use the re module to compile patterns and search/match in strings.
Question: What is the difference between subprocess.call and subprocess.Popen?
Answer: subprocess.call runs a command and waits for it to finish; Popen gives more
control, allowing asynchronous execution and interaction.
Question: What are weak references?
Answer: References that do not prevent their object from being garbage-collected,
useful for caching.
Question: How do you implement a plugin architecture?
Answer: Use dynamic imports, the importlib module, or entry points like in setuptools.
Question: What is the difference between staticmethod and instance method?
Answer: Instance methods take self; static methods do not take self or cls.
Question: Explain the difference between shallow and deep equality.
Answer: Shallow equality checks top-level elements; deep equality checks all nested
elements.
Question: How do you make a dictionary ordered?
Answer: In Python 3.7+, dicts maintain insertion order by default.
Question: What are dataclasses in Python?
Answer: Introduced in Python 3.7, @dataclass decorator simplifies class boilerplate for
storing data.
Question: How do you prevent a Python script from being imported as a module?
Answer: Wrap code in if __name__ == "__main__":
Question: How do you use the assert statement?
Answer: assert condition, "error message", raises AssertionError if condition is false.
Question: How can you profile Python code?
Answer: Use cProfile, profile, or timeit modules.
Question: What is the difference between __getattr__ and __getattribute__?
Answer: __getattribute__ is always called; __getattr__ is called only if attribute is not
found.
Question: How do you merge lists without duplicates?
Answer: merged = list(set(list1) | set(list2))
Question: How do you implement a queue in Python?
Answer: Use collections.deque or queue.Queue for thread-safe queues.
Question: What is the difference between == and is with None?
Answer: Use is to check identity with None: if x is None:
Question: When would you use __del__?
Answer: __del__ is a destructor method. Use with caution for resource cleanup.
Question: What are the main differences between Python 2 and 3?
Answer: Print function syntax, integer division, Unicode support, and libraries. Python 3
is recommended.
Question: How do you remove duplicates from a list?
Answer: list(set(my_list))
Question: How do you flatten a nested list?
Answer: Use recursion or list comprehension. For 2D: [item for sublist in nested for item
in sublist]
Question: How do you get the memory address of an object?
Answer: id(obj)
Question: How do you implement private methods in Python?
Answer: Prefix method names with double underscores (__method), using name
mangling.
Question: How do you sort a dictionary by value?
Answer: sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
Question: How do you make a function accept only keyword arguments?
Answer: Use * in the parameter list: def func(*, arg1, arg2):
Question: How do you implement property-based testing?
Answer: Use libraries like hypothesis for generating test cases based on properties.
Question: How do you implement memoization?
Answer: Use functools.lru_cache or a custom decorator to cache results.
Question: How do you raise custom exceptions?
Answer: raise MyException("error message")
Question: How do you check if a string is a palindrome?
Answer: s == s[::-1]
Question: How do you use itertools in Python?
Answer: itertools provides efficient looping utilities such as product, permutations,
combinations.
Question: How do you set a function’s default parameter to be mutable?
Answer: It is discouraged as it can lead to bugs. Use None as the default and set within
the function.
Question: What are magic variables like __name__?
Answer: Special variables built into Python that provide context about the runtime
environment.
Question: How do you perform binary search?
Answer: Use bisect module: bisect.bisect_left(list, item)
Question: How do you convert a list to a string?
Answer: ''.join(list)
Question: What is the use of the else clause in loops?
Answer: The else block after a loop runs if the loop wasn’t terminated by break.
Question: How do you run a Python script as a background process?
Answer: Use python script.py & (Unix) or start /B python script.py (Windows).
Question: How do you enforce immutability in a class?
Answer: Override __setattr__ to prevent attribute assignment after creation.
Question: How do you use function annotations?
Answer: Use def func(a: int, b: str) -> bool:
Question: How do you dynamically execute Python code?
Answer: Use eval() for expressions and exec() for statements, but use with extreme
caution for security.
Question: What is the difference between del and remove()?
Answer: del deletes an object/element by index; remove() removes by value.
Question: How do you zip two lists of unequal length?
Answer: Use itertools.zip_longest()
Question: What is the difference between threading and asyncio?
Answer: threading uses OS threads, asyncio uses single-threaded event loops for
concurrency.
Question: How do you create a class attribute at runtime?
Answer: Assign directly: MyClass.new_attr = value
Question: How can you make a dictionary comprehension?
Answer: {k: v for k, v in iterable}
Question: How do you import a module from a different directory?
Answer: Modify sys.path or use relative imports within a package.
Conclusion
Mastering these advanced Python questions and answers will help you excel in
technical interviews and build robust, efficient code. Continue practicing,
experimenting, and staying updated with Python’s latest features!