1. Python Basics
What is Python and its key features?
What is Python and its key features?
What are Python's built-in data types?
What are Python's built-in data types?
What is the difference between lists and tuples?
What is the difference between lists and tuples?
Explain Python's mutable and immutable types
Explain Python's mutable and immutable types
list_a = [1, 2, 3]; list_a[0] = 10
works, but string_a = 'hello'; string_a[0] = 'H' raises TypeError.What are Python's identity operators?
What are Python's identity operators?
is and is not. They check if two
variables reference the same object in memory, not just equal values. Example:
a = [1,2,3]; b = a; c = [1,2,3]. Here a is b returns True, but a is c
returns False even though a == c returns True.What is the difference between global and local variables?
What is the difference between global and local variables?
global keyword inside function to
modify global variable. Example: python x = 10 # global def func(): y = 5 # local global x x = 20 # modifies global Local variables shadow global ones
with same name unless global is used.What is the difference between range() and xrange() (Python 2 vs 3)?
What is the difference between range() and xrange() (Python 2 vs 3)?
range() returns list, xrange() returns generator (memory
efficient). In Python 3: range() behaves like Python 2’s xrange()
(returns range object, not list), xrange() removed. Python 3’s range() is
memory efficient and lazy. Use list(range(10)) to get list if needed.How does Python handle type casting?
How does Python handle type casting?
int(), float(),
str(), bool(), list(), tuple(), set(), dict(). These create new
objects of specified type. Example: int('123') returns 123, str(42)
returns '42', list('abc') returns ['a', 'b', 'c']. Implicit conversion
happens in some contexts (e.g., arithmetic operations).What is PEP 8 and why is it important?
What is PEP 8 and why is it important?
flake8 and black help enforce PEP 8.What is the Zen of Python?
What is the Zen of Python?
import this. Key principles include: “Beautiful is better than ugly”, “Simple is better than complex”, “Readability counts”, “There should be one obvious way to do it”, “Errors should never pass silently”, “In the face of ambiguity, refuse the temptation to guess”. These principles emphasize simplicity, readability, and explicit over implicit.2. Data Structures
How do you create and manipulate lists?
How do you create and manipulate lists?
my_list = [1, 2, 3] or list() constructor. Common operations: append() adds element at end, insert(index, item) inserts at position, remove(item) removes first occurrence, pop() removes and returns last element, extend() adds elements from another list, sort() sorts in place, reverse() reverses order.What are list comprehensions?
What are list comprehensions?
[expression for item in iterable if condition]. Examples: squares = [x**2 for x in range(10)], evens = [x for x in range(20) if x % 2 == 0], matrix = [[i*j for j in range(3)] for i in range(3)].Explain Python dictionaries and their methods
Explain Python dictionaries and their methods
get(key, default), keys(), values(), items(), update(), pop(key), popitem(), clear(), setdefault(). Example: person = {'name': 'John', 'age': 30}.What is the difference between sets and frozensets?
What is the difference between sets and frozensets?
set(). Frozensets are immutable versions created with frozenset().
Sets support add(), remove(), discard() while frozensets don’t.
FrozenSets can be used as dictionary keys or elements of other sets.How do you perform set operations?
How do you perform set operations?
|), intersection (&),
difference (-), symmetric difference (^). Also available as methods:
union(), intersection(), difference(), symmetric_difference().
Example: set1 = {(1, 2, 3)}; set2 = {(3, 4, 5)}; union = set1 | set2 returns
{(1, 2, 3, 4, 5)}.What is the difference between list, tuple, and set?
What is the difference between list, tuple, and set?
[]. Allow duplicates, indexed
access, support modification. Tuples are ordered, immutable sequences
using (). Allow duplicates, indexed access, cannot be modified. Sets are
unordered, mutable collections of unique elements using {} or set(). No
duplicates, no indexing, fast membership testing. Use lists for ordered,
changeable data; tuples for fixed, ordered data; sets for unique, unordered
collections.What is the difference between deepcopy and shallow copy?
What is the difference between deepcopy and shallow copy?
copy.copy()) creates new object but references same nested objects. Changes to nested objects affect both. Deep copy (copy.deepcopy()) creates completely independent copy including all nested objects. Changes to nested objects don’t affect original. Example:3. Object-Oriented Programming
What are the four pillars of OOP in Python?
What are the four pillars of OOP in Python?
How do you create a class in Python?
How do you create a class in Python?
class keyword followed by class name (PascalCase). Define __init__ method as constructor. Use self parameter to refer to instance. Example:Explain instance, class, and static methods
Explain instance, class, and static methods
self, operate on instance data. Class methods
take cls, decorated with @classmethod, operate on class-level data.
Static methods take neither, decorated with @staticmethod, utility
functions logically grouped with class.What is inheritance?
What is inheritance?
super() to call
parent methods. Python uses Method Resolution Order (MRO) for multiple
inheritance.What are magic methods (dunder methods)?
What are magic methods (dunder methods)?
__init__, __str__). They enable operator overloading and customize class behavior. Common ones: __init__ (constructor), __str__ (string representation), __repr__ (official representation), __len__, __add__, __eq__.What are __slots__ in Python classes and why use them?
What are __slots__ in Python classes and why use them?
__slots__ is class variable that restricts attributes to those listed.
Prevents creation of __dict__ for instances, saving memory. Useful for
classes with many instances. Trade-off: can’t add new attributes dynamically.
Example: python class Person: __slots__ = ['name', 'age'] def __init__(self, name, age): self.name = name self.age = age Reduces memory
overhead significantly for large numbers of instances.Explain property decorators (@property, setter, deleter)
Explain property decorators (@property, setter, deleter)
@property defines getter, @property_name.setter defines setter, @property_name.deleter defines deleter. Enables computed attributes, validation, encapsulation. Example:How does Python implement Method Resolution Order (MRO)?
How does Python implement Method Resolution Order (MRO)?
ClassName.__mro__ or ClassName.mro(). Ensures consistent, predictable method resolution. Example: class D(B, C): pass searches D → B → C → object. super() uses MRO to call next method in chain.4. Functions and Decorators
What are *args and **kwargs?
What are *args and **kwargs?
*args allows function to accept variable number of positional arguments as tuple. **kwargs allows variable number of keyword arguments as dictionary. Useful for flexible function signatures. Example: func(1, 2, 3, name='John', age=30) where args=(1, 2, 3) and kwargs={'name': 'John', 'age': 30}.What are lambda functions?
What are lambda functions?
lambda keyword.
Limited to single expression. Syntax: lambda arguments: expression. Commonly
used with map(), filter(), sorted(). Example: square = lambda x: x**2,
evens = list(filter(lambda x: x % 2 == 0, numbers)).What are decorators in Python?
What are decorators in Python?
@decorator syntax. Take function as argument,
return modified function. Used for logging, timing, authentication, caching.
Example:What is a closure?
What is a closure?
What are generator functions and yield?
What are generator functions and yield?
yield instead of return to produce values lazily, one at a time. They maintain state between calls. More memory efficient for large sequences. Example:Explain function annotations and their use cases
Explain function annotations and their use cases
def func(param: type) -> return_type:. Stored in
__annotations__ attribute. Not enforced by Python but useful for
documentation, type checking tools (mypy), IDEs. Example:How does duck typing work in Python?
How does duck typing work in Python?
5. File Handling and I/O
How do you read and write files?
How do you read and write files?
open() function with mode: ‘r’ for read, ‘w’ for write, ‘a’ for append, ‘r+’ for read/write. Use with statement for automatic cleanup. read() reads entire file, readline() reads one line, readlines() returns list of lines. Example:What is the difference between 'w' and 'a' file modes?
What is the difference between 'w' and 'a' file modes?
How do you work with CSV files?
How do you work with CSV files?
csv module. csv.reader() reads CSV files, csv.writer() writes.
csv.DictReader() and csv.DictWriter() work with dictionaries. Example:How do you work with JSON?
How do you work with JSON?
json module. json.dumps() converts Python object to JSON string. json.loads() parses JSON string to Python object. json.dump() writes to file. json.load() reads from file. Example:What are context managers?
What are context managers?
with statement ensures proper acquisition and release of resources. Implements __enter__ and __exit__ methods. Commonly used for file operations, database connections, locks.6. Exception Handling
What is exception handling?
What is exception handling?
try-except blocks. try block contains code that might raise exception. except block handles specific exceptions. Multiple except blocks possible. Prevents program termination.What are common built-in exceptions?
What are common built-in exceptions?
ZeroDivisionError (division by zero), ValueError
(invalid value), TypeError (wrong type), IndexError (invalid index),
KeyError (key not found in dict), FileNotFoundError (file doesn’t exist),
AttributeError (invalid attribute), ImportError (import fails).What is try-except-else-finally?
What is try-except-else-finally?
How do you create custom exceptions?
How do you create custom exceptions?
Exception class. Add custom
attributes and methods. Raise with raise keyword. Example:What are assertions?
What are assertions?
assert statement. If condition false, raises AssertionError. Disabled when optimization flag used. Use for debugging, not error handling. Syntax: assert condition, message. Example: assert len(numbers) > 0, 'List cannot be empty'.7. Modules and Packages
What is the difference between module and package?
What is the difference between module and package?
__init__.py file. Packages organize related modules hierarchically. Import modules with import statement, packages with dot notation.How do you import modules?
How do you import modules?
import module imports entire module, from module import name
imports specific items, from module import * imports all (not recommended),
import module as alias creates alias. Example: import math, from datetime import datetime, import pandas as pd.What is __init__.py?
What is __init__.py?
__init__.py makes directory a Python package. Can be empty or contain
initialization code. Executed when package imported. Defines what’s exported
with __all__. In Python 3.3+, namespace packages don’t require
__init__.py, but it’s still recommended for clarity.What is the __name__ variable?
What is the __name__ variable?
__name__ is special variable set by Python. When file executed directly,
__name__ == '__main__'. When imported as module, __name__ equals module
name. Common pattern: if __name__ == '__main__': allows code to run only
when file executed directly, not when imported.How do you create virtual environments?
How do you create virtual environments?
8. Advanced Python Concepts
What are iterators and iterables?
What are iterators and iterables?
__iter__). Iterator is object that returns next value (implements __next__). Lists, tuples, strings are iterables. iter() creates iterator from iterable. next() gets next value. StopIteration raised when exhausted.What is multithreading vs multiprocessing?
What is multithreading vs multiprocessing?
threading module.
Multiprocessing: Separate processes, true parallelism, good for CPU-bound
tasks. Use multiprocessing module. Heavier than threads.What is the Global Interpreter Lock (GIL)?
What is the Global Interpreter Lock (GIL)?
What are metaclasses?
What are metaclasses?
type is
default metaclass. Classes are instances of metaclasses. Used for class
creation customization, ORMs, API frameworks. Advanced concept, rarely needed.
Define by inheriting from type.What are coroutines and async/await?
What are coroutines and async/await?
async def. Use await to pause until result available. Enables asynchronous
programming. Non-blocking I/O operations. Use asyncio module. More efficient
than threads for I/O-bound concurrent tasks.What is the difference between comprehensions (list/dict/set/generator)?
What is the difference between comprehensions (list/dict/set/generator)?
if clause. Generator comprehensions use parentheses and don’t create full collection in memory.How does Python's garbage collector work?
How does Python's garbage collector work?
gc module: gc.collect() forces collection, gc.disable()
disables cyclic GC. Uses generational approach: objects in different
generations based on age.What are coroutines in Python?
What are coroutines in Python?
async def. Return coroutine object when called. Use await to pause until awaited coroutine completes. Enable cooperative multitasking. Managed by event loop (asyncio.run()). Example:9. Web Development with Python
What are popular Python web frameworks?
What are popular Python web frameworks?
How do you create a simple Flask application?
How do you create a simple Flask application?
What is Django ORM?
What is Django ORM?
How do you handle HTTP requests?
How do you handle HTTP requests?
requests library for making HTTP requests. GET, POST, PUT, DELETE
methods. Handle responses, status codes, headers, JSON. Example: python import requests response = requests.get('https://api.example.com/data') if response.status_code == 200: data = response.json() What is REST API?
What is REST API?
10. Data Science and Libraries
What is NumPy and why is it used?
What is NumPy and why is it used?
What is pandas and its main data structures?
What is pandas and its main data structures?
How do you handle missing data in pandas?
How do you handle missing data in pandas?
isnull() and notnull() detect missing values. dropna()
removes rows/columns with NaN. fillna() fills NaN with value.
interpolate() fills based on interpolation. isna() checks for missing.
Different strategies for different scenarios.What is matplotlib?
What is matplotlib?
pyplot module provides MATLAB-like interface. Line plots,
scatter plots, bar charts, histograms. Customizable colors, labels, legends.
Save figures to files.What is scikit-learn used for?
What is scikit-learn used for?
11. Additional Important Topics
What is list slicing?
What is list slicing?
sequence[start:end:step]. start is inclusive, end is exclusive. Negative indices count from end. Omitting values uses defaults. Creates shallow copy. Example: lst[1:4] gets elements 1-3, lst[::-1] reverses list.What is the difference between '==' and 'is'?
What is the difference between '==' and 'is'?
== compares values (equality). is checks if objects are same in memory
(identity). Use == for value comparison. Use is primarily with None
checks. Example: a = [1,2]; b = [1,2]; a == b is True, a is b is False.What are Python's logical operators?
What are Python's logical operators?
and (returns True if both operands are True), or
(returns True if at least one is True), not (negates boolean value).
Short-circuit evaluation: and stops at first False, or stops at first
True.What is the enumerate() function?
What is the enumerate() function?
enumerate() adds counter to iterable, returns enumerate object yielding
tuples of (index, value). Useful in loops when you need both index and value.
Start parameter specifies starting index (default 0). Example: for index, fruit in enumerate(fruits):What is the zip() function?
What is the zip() function?
zip() combines multiple iterables element-wise into tuples. Returns iterator of tuples. Stops at shortest iterable. Use zip(*zipped) to unzip. Useful for parallel iteration. Example: for name, age in zip(names, ages):12. Core Programming Concepts
What is the difference between append() and extend()?
What is the difference between append() and extend()?
What are default arguments in functions?
What are default arguments in functions?
def greet(name, message='Hello'):What is the difference between remove(), pop(), and del?
What is the difference between remove(), pop(), and del?
What is string formatting?
What is string formatting?
str.format() method, f-strings
(formatted string literals). f-strings are most modern and readable (Python
3.6+). Support expressions inside . Example: f'{name} is {age} years old',
f'{name.upper()} is {age * 2}'.What are the any() and all() functions?
What are the any() and all() functions?
any() returns True if at least one element in iterable is True. all() returns True if all elements are True. Short-circuit evaluation. Empty iterable: any() returns False, all() returns True. Useful for checking conditions on sequences.13. Python Internals and Memory Management
How does Python handle memory management?
How does Python handle memory management?
gc module.What is Python's memory model (pass-by-object-reference)?
What is Python's memory model (pass-by-object-reference)?
What is object interning in Python?
What is object interning in Python?
a = 256; b = 256; a is b returns True (same object). a = 257; b = 257; a is b may return False (different objects). Interning saves
memory and speeds up comparisons. Can force interning with sys.intern() for
strings.What are weak references in Python?
What are weak references in Python?
weakref module. Don’t increase reference count. Useful for caches, circular references, observer patterns. Example:How does CPython differ from PyPy or Jython?
How does CPython differ from PyPy or Jython?
How can you inspect CPython bytecode?
How can you inspect CPython bytecode?
dis module to disassemble Python code into bytecode. Shows what CPython interpreter executes. Useful for understanding performance, debugging, learning Python internals. Example:14. Descriptors and Magic Methods
How do properties work under the hood? Explain the descriptor protocol
How do properties work under the hood? Explain the descriptor protocol
__get__, __set__, __delete__. Descriptors are objects that define these methods. When accessing attribute, Python checks if it’s descriptor and calls appropriate method. @property creates descriptor. Example:What is the difference between __getattr__ and __getattribute__?
What is the difference between __getattr__ and __getattribute__?
__getattr__: called only when attribute not found through normal lookup
(after __dict__, class hierarchy). Last resort. __getattribute__:
called for every attribute access, even if attribute exists. Must call
object.__getattribute__() to avoid recursion. More powerful but dangerous.
Example:__getattr__ for fallback, __getattribute__ for complete control (with caution).How can you create a class without using the class keyword?
How can you create a class without using the class keyword?
type() metaclass to create classes dynamically. type(name, bases, dict) creates new class. Example:class keyword is syntactic sugar for type() call. Understanding this explains what metaclasses are.Explain monkey patching with an example
Explain monkey patching with an example
15. Advanced Generators and Iterators
What is the yield from statement (PEP 380)?
What is the yield from statement (PEP 380)?
yield from delegates to another generator, simplifying generator composition. More than syntax sugar: handles sub-generator exceptions, sends values to sub-generator, returns value from sub-generator. Example:yield from also handles send(), throw(), and close() properly, making it essential for generator composition.How does generator execution and frame persistence work?
How does generator execution and frame persistence work?
next() called,
function executes until yield, then pauses, preserving local state. Frame
persists between calls. Example:How can you inspect Python bytecode?
How can you inspect Python bytecode?
dis module to disassemble Python code into bytecode instructions. Shows what CPython interpreter executes. Useful for understanding performance, debugging, learning internals. Example:16. Advanced Concurrency and Parallelism
Why does the threading module exist if GIL prevents true parallelism?
Why does the threading module exist if GIL prevents true parallelism?
When to choose ThreadPoolExecutor vs ProcessPoolExecutor vs asyncio?
When to choose ThreadPoolExecutor vs ProcessPoolExecutor vs asyncio?
What are the resource implications (memory, CPU) of each concurrency approach?
What are the resource implications (memory, CPU) of each concurrency approach?
How does async/await differ from threading?
How does async/await differ from threading?
How do you profile and solve real-world performance bottlenecks?
How do you profile and solve real-world performance bottlenecks?
cProfile for function-level profiling, line_profiler
for line-level, memory_profiler for memory usage. Identify bottlenecks, then
optimize: use appropriate concurrency (threading/multiprocessing/asyncio),
optimize algorithms, use efficient data structures, cache results, avoid
premature optimization. Example:What are the real-world use cases for multithreading, multiprocessing, and asyncio?
What are the real-world use cases for multithreading, multiprocessing, and asyncio?
17. Design Patterns and Architecture
How do you apply SOLID principles in Python?
How do you apply SOLID principles in Python?
abc.ABC for interfaces, composition over inheritance.Why prefer composition over inheritance? Provide a practical refactoring example
Why prefer composition over inheritance? Provide a practical refactoring example
How would you implement a Factory pattern in Python?
How would you implement a Factory pattern in Python?
What are four different ways to implement Singleton in Python, and their trade-offs?
What are four different ways to implement Singleton in Python, and their trade-offs?
How do functions as first-class objects make Strategy pattern unnecessary?
How do functions as first-class objects make Strategy pattern unnecessary?
How do you write a context manager from scratch (class-based and @contextmanager)?
How do you write a context manager from scratch (class-based and @contextmanager)?
@contextmanager is simpler for basic cases.What are key principles for designing RESTful APIs in Python?
What are key principles for designing RESTful APIs in Python?
How do you resolve circular dependencies?
How do you resolve circular dependencies?
What is monkey patching and when would you use it?
What is monkey patching and when would you use it?
18. Testing and Debugging
How do you decide what to mock in tests?
How do you decide what to mock in tests?
What is the difference between mocking and stubbing?
What is the difference between mocking and stubbing?
unittest.mock, Mock() can do both. Example:What are the dangers of over-mocking in test suites?
What are the dangers of over-mocking in test suites?
How do you debug Python code effectively?
How do you debug Python code effectively?
logging module instead of printpython -m pdb script.py after crashEssential pdb Commands
n(next): Execute current lines(step): Step into functionc(continue): Continue executionl(list): Show current code contextp variable: Print variable valuepp variable: Pretty-print variableq(quit): Exit debugger
What is pdb and how do you use it?
What is pdb and how do you use it?
pdb is Python’s built-in debugger. Interactive debugging tool. Start with
python -m pdb script.py or insert import pdb; pdb.set_trace() in code.
Commands: n (next line), s (step into function), c (continue), l (list
code), p variable (print variable), pp variable (pretty print), w
(where/stack trace), u (up stack), d (down stack), q (quit). Example:How do you use logging for debugging?
How do you use logging for debugging?
logging module instead of print() statements. Configure log levels:
DEBUG, INFO, WARNING, ERROR, CRITICAL. Add context: function names, line
numbers, timestamps. Example:How do you debug exceptions and tracebacks?
How do you debug exceptions and tracebacks?
traceback module to analyze exceptions. traceback.print_exc() prints
full traceback. traceback.format_exc() returns traceback as string. Use
sys.exc_info() to get exception info. Example:logging.exception() to log exceptions with traceback. Understand stack traces: read from bottom up to find root cause.What are common debugging techniques in Python?
What are common debugging techniques in Python?
How do you debug performance issues in Python?
How do you debug performance issues in Python?
How do you debug memory leaks in Python?
How do you debug memory leaks in Python?
gc module to inspect objects. Use tracemalloc to track memory allocations. Use memory_profiler for line-by-line memory usage. Check for circular references, unclosed resources, large data structures. Example:objgraph to visualize object references. Close file handles, database connections. Use context managers (with statement) for automatic cleanup.Conclusion & Interview Tips
This comprehensive guide covers 150+ essential Python interview questions across all major categories including basics, data structures, OOP, functions, file handling, exception handling, modules, advanced concepts, Python internals, memory management, descriptors, generators, concurrency, design patterns, architecture, testing, web development, and data science.Key Interview Preparation Tips
- Master Python fundamentals before diving into frameworks
- Practice coding problems on platforms like LeetCode and HackerRank
- Build real projects to demonstrate practical skills
- Understand memory management and performance implications
- Study common algorithms and data structure implementations
- Review Python’s standard library and popular third-party packages
- Prepare for both theoretical and practical coding questions
During the Interview
- Read questions carefully and ask for clarification
- Explain your thought process while solving problems
- Write clean, readable code with proper variable names
- Consider edge cases and error handling
- Discuss time and space complexity of your solutions
- Be honest about what you don’t know but show willingness to learn
Technical Skills to Demonstrate
- Strong understanding of Python syntax and semantics
- Proficiency with data structures and algorithms
- Object-oriented programming principles
- Error handling and debugging skills
- Knowledge of Python ecosystem and libraries
- Problem-solving and analytical thinking
- Code optimization and performance awareness