50 Python Interview Questions PDF 1748080994
50 Python Interview Questions PDF 1748080994
@Tajamulkhann
1. What is Python and what are its
key features?
Python is a high-level, interpreted
programming language known for:
Easy-to-read syntax
n n
Dynamic typing
h a
Garbage collection
u l k
m
Extensive standard library
ja
a
Support for multiple programming
T
@ paradigms (OOP, functional, procedural)
Portable and platform-independent
Strong community support and
comprehensive documentation
@Tajamulkhann
2. Explain the difference between
lists and tuples.
Lists
Mutable (can be modified after creation)
Defined using square brackets: [1, 2, 3]
Memory overhead is larger
n n
h a
Better for data that changes frequently
u l k
Tuples
ja m
a
Immutable (cannot be modified after
T
@ creation)
Defined using parentheses: (1, 2, 3)
More memory efficient
Faster iteration than lists
Can be used as dictionary keys (lists
cannot)
@Tajamulkhann
3. What is PEP 8?
Indentation (4 spaces)
n n
h a
Maximum line length (79 characters)
l k
Naming conventions (e.g., snake_case for
u
m
functions and variables)
ja
a
Comments and docstring formatting
T
@ Whitespace usage
Import organization
@Tajamulkhann
4. What is the Global Interpreter Lock
(GIL) in Python?
The GIL is a mutex that protects access to
Python objects, preventing multiple threads
from executing Python bytecode
simultaneously.
n n
h a
Key implications:
u l k
m
Only one thread can execute Python code at
ja
a
once.
T
@ CPU-bound Python programs don't benefit
from multithreading.
I/O-bound programs can still benefit from
threading
The GIL is specific to CPython (the standard
implementation)
@Tajamulkhann
5. How is memory managed in
Python?
Python uses automatic memory management
with:
Private heap space that stores all objects
and data structures
n n
Memory manager that handles
h a
l k
allocation/deallocation
u
ja m
Garbage collector that reclaims memory
from objects no longer referenced
T a
Reference counting as primary mechanism
@ for memory management
Cycle detector to handle reference cycles
Memory management is hidden from the
programmer, who doesn't need to allocate or
free memory manually.
@Tajamulkhann
6. What are decorators in Python?
Decorators are functions that modify the
behavior of other functions or methods without
changing their source code. They use the
@decorator syntax and wrap a function,
enabling code reuse and separation of
n n
concerns.
h a
Example:
@timer u l k
ja m
def some_function():
T
pass a
@
Common use cases:
Logging and timing functions
Access control and authentication
Caching function results
Input validation and error handling
@Tajamulkhann
7. What are generators in Python?
Generators are functions that use the 'yield'
keyword to return values one at a time,
suspending & resuming their state between
calls.
n
Allow iteration without creating entire
n
sequence in memory
h a
l k
Are memory efficient for large data sets
u
Are created using functions with 'yield' or
ja m
generator expressions
T a
Support the iterator protocol (iter, next)
@ Can be consumed only once
Example:
def count_up_to(n):
i=0
while i < n:
yield i
i += 1
@Tajamulkhann
8. What is the difference between
shallow copy and deep copy?
Shallow Copy
Duplicates only the top‐level container;
inner elements remain shared.
n n
Mutating nested items reflects in both the
original and the copy.
h a
l k
Use via copy.copy() or .copy().
u
ja m
a
Deep Copy
T
@ Recursively clones the container and all
nested objects.
Modifications in the copy never affect the
original.
Use via copy.deepcopy().
@Tajamulkhann
9. What are Python namespaces?
n n
h a
Python has four types of namespaces:
u l k
Local: Inside current function
m
Enclosing: Names in outer functions
ja
a
Global: At the module level
T
@ Built-in: Contains built-in functions and
exceptions
@Tajamulkhann
10. Mutable and Immutable objects
Mutable Objects
Their state can change after creation (e.g.,
lists, dicts, sets, custom classes).
Passed into functions, in-place edits modify
the original.
n n
h a
Maintain a variable internal state.
u l k
m
Immutable Objects
ja
a
Cannot be altered once created (e.g.,
T
@numbers, strings, tuples, frozensets).
“Modifications” yield entirely new objects.
Hashable—safe to use as dictionary keys or
set elements.
@Tajamulkhann
11. What are Python iterators?
Iterator Protocol
Defines __iter__() (returns the iterator) and
__next__() (yields the next item or raises
StopIteration).
n n
Iterators
h a
u l k
Traverse elements one by one without
indexing.
ja m
a
Obtained by calling iter() on an iterable.
T
@ Get “used up” as you loop through them.
Highly memory-efficient for large or
streaming data.
Power for-loops, generator functions, and
comprehensions.
@Tajamulkhann
12. __str__ vs __repr__ ?
__str__
Invoked by str() and print()
Returns a human-friendly description of the
object
Aimed at end-users
n n
h a
__repr__
u l k
m
Invoked by repr() and in the REPL
ja
a
Returns an unambiguous, ideally evaluable
T
@string (e.g., ClassName(args…))
Aimed at developers for debugging and
inspection
Serves as a fallback for __str__ if the latter
isn’t defined
@Tajamulkhann
13. Garbage collection mechanism.
Reference Counting
Tracks active references to each object
Immediately frees an object’s memory
when its count drops to zero
Generational Garbage Collection
n n
a
Organizes objects into three “generations”
h
by age
u l k
Frequently scans young objects for cycles;
ja m
survivors promote to older generations
T a
Efficiently reclaims cyclic references that
@ reference counting can’t catch
Manual Control (gc module)
gc.enable() / gc.disable() to toggle
collection
gc.collect() to force an immediate cleanup
of all generations
@Tajamulkhann
14. Metaclasses in Python?
Metaclasses
Classes that define how other classes are
constructed and behave.
Every class is an instance of a metaclass—
type by default.
n n
a
Create a custom metaclass by subclassing
h
l k
type and overriding __new__/__init__.
u
Use to inject attributes/methods, enforce
ja m
patterns, or register classes automatically.
T a
Common Applications
@Auto-adding methods or properties to
classes
Building ORM frameworks that register
models
Enforcing coding standards or design
patterns at class creation time
@Tajamulkhann
15. What are context managers?
Context managers control resource
acquisition and release using the 'with'
statement.
Implement __enter__ and __exit__
methods
n n
a
Ensure proper cleanup of resources
h
Can be created using u l k
Handle exceptions raised within the block
ja m
'contextlib.contextmanager' decorator.
T a
Common examples:
@ File operations (with open('file.txt') as f:)
Database connections
Locks in threading
Benefits: Cleaner code with guaranteed
resource cleanup, Exception safety,
Encapsulation of setup/teardown logic
@Tajamulkhann
16. What is duck typing in Python?
Duck typing is a programming concept where
an object's suitability is determined by its
behavior (methods and properties) rather than
its class or type.
n n
a
"If it walks like a duck and quacks like a duck,
h
it's a duck"
u l k
Key aspects:
ja m
T a
Focus on what an object can do, not what it
@ is
No explicit interface requirement
Emphasizes behavior over inheritance
Supports polymorphism without formal
hierarchies
Core to Python's dynamic and flexible
nature
@Tajamulkhann
17. What are lambda functions?
Lambda functions are anonymous, inline
functions defined using the 'lambda'
keyword: lambda arguments: expression
Characteristics:
n n
a
Single expression only (no statements)
h
u l k
Can take multiple arguments
Return the value of the expression
ja m
Can be assigned to variables or passed as
T a
arguments
@
Commonly used with map(), filter(), and
sorted()
Example:
square = lambda x: x*x
sorted_lst = sorted(items, key=lambda x: len(x))
@Tajamulkhann
18. *args vs **kwargs.
*args
Collects positional arguments into a tuple
Allows functions to accept variable number
of positional arguments
n
Convention is to use 'args' but any name
n
with * works
h a
l k
Example def func(*args): print(args)
u
**kwargs:
ja m
T a
Collects keyword arguments into a
@ dictionary
Allows functions to accept variable number
of keyword arguments
Convention is to use 'kwargs' but any name
with ** works
Example def func(**kwargs): print(kwargs)
@Tajamulkhann
19. Pillars of OOP?
Encapsulation:
Groups data and methods inside a class and
restricts direct access to some parts, protecting
the object’s data.
Abstraction:
n n
a
Hides complex implementation details and
h
l k
exposes only the necessary features to the user.
Inheritance: u
ja m
Allows a class (child) to inherit properties and
T a
behaviors from another class (parent),
@
promoting code reuse.
Polymorphism:
Lets objects of different classes respond
differently to the same method call, enabling
flexible and interchangeable code.
@Tajamulkhann
20. SOLID principle in OOP design?
Single Responsibility Principle: A class should
have only one job.
n
extendable without modifying existing code.
n
h a
u
be usable in place of their l k
Liskov Substitution Principle: Subclasses
parent classes
should
j
without issues.
a m
T a
@
Interface Segregation Principle: Use many
small, specific interfaces instead of one big one.
@Tajamulkhann
21. What is the use of self in Python?
Represents the instance of a class
Is the first parameter of instance methods
Allows access to attributes and methods of
the instance
n
Creates a way to refer to the specific
n
instance being operated on
h a
universally adoptedu l k
Is a convention (not a keyword), but
ja m
T a
Example:
@
class MyClass:
def __init__(self, value):
self.value = value #Instance variable
def my_method(self):
return self.value #access instance variable
@Tajamulkhann
22. Python's magic methods?
"Magic methods (dunder methods) are special
methods with double underscores:
__init__(): Object initialization
__str__(), __repr__(): String representation
n
__len__(), __getitem__(): Container behavior
n
a
__add__(), __sub__(): Operator overloading
h
protocol u l k
__enter__(), __exit__(): Context manager
ja m
__iter__(), __next__(): Iterator protocol
T a
__call__(): Make objects callable
@
__eq__(), __lt__(): Comparison operations
@Tajamulkhann
23. Purpose of __init__.py file?
_init__.py is a special Python file used to
indicate that a directory is a Python package.
Key Points:
n
Executed when the package or its modules
n
are imported
h a
u l k
Can be empty or include initialization logic
Can define __all__ to control from package
import *
ja m
T a
Useful for setting up package-level
@ variables and imports
Required in Python 2, optional in Python 3
Helps expose a clean API and hide internal
modules
@Tajamulkhann
24. @staticmethod vs @classmethod
_init__.py is a special Python file used to
indicate that a directory is a Python package.
Key Points:
n
Executed when the package or its modules
n
are imported
h a
u l k
Can be empty or include initialization logic
Can define __all__ to control from package
import *
ja m
T a
Useful for setting up package-level
@ variables and imports
Required in Python 2, optional in Python 3
Helps expose a clean API and hide internal
modules
@Tajamulkhann
25. Instance Var vs Class Attribute
n
Typically inside the
Defined In class body
__init__ method
a n
(outside methods)
Accessed With
l
self.variable_name
k h
ClassName.variable_name
u
or self.variable_name
Storage
ja m
Stored in the instance's Stored in the class's
a
__dict__ __dict__
@ T
Overrides?
Can override class
attribute with same
No override
unless redefined
name on the instance inside the instance
@Tajamulkhann
26. Method Overridng vs Overloading
Overriding Overloading
n
from the parent class arguments
a n
Yes – used in
l k h No – done within
Inheritance?
m u
parent-child class
relationships
the same class
a ja
@ T
Purpose
Change or extend
base class behavior
Allow one method to
handle multiple input
patterns
class Dog(Animal):
def hi(self, name=None):
Example def speak():
pass
pass
@Tajamulkhann
27. Python modules and packages?
Modules:
Single Python file containing code
(functions, classes, variables)
Imported using 'import module_name'
Provide a way to organize related code
n n
Accessed using dot notation:
h a
module_name.function()
u l k
Packages:
ja m
T a
Collection of related modules in a directory
@ Must contain an __init__.py file (in Python 2,
optional in Python 3)
Enable hierarchical organization of modules
Imported using 'import package.module'
Can be distributed and installed using pip
@Tajamulkhann
28. Multithreading and its limitations.
Implemented using the 'threading' module
Creates multiple threads within a single
process
Shares the same memory space
Limitations:
n n
a
Global Interpreter Lock (GIL) prevents true
h
l k
parallel execution of Python code
u
Only one thread can execute code at once
ja m
Effective for I/O-bound tasks but not CPU-
T a
bound tasks
@ Alternative solutions for CPU-bound tasks :
multiprocessing module (uses multiple
processes)
concurrent.futures module - Using C
extensions that release the GIL
@Tajamulkhann
29. Yield keyword in Python?
yield turns a function into a generator, allowing
it to return values one at a time while pausing
execution and preserving state.
Key Points:
n n
a
Pauses and resumes function execution
h
u l
Enables lazy evaluation
k
Maintains internal state between calls
ja m
Saves memory (ideal for large or infinite
T a
data)
@
def gen():
yield 1
yield 2
g = gen()
next(g) # 1
next(g) # 2
@Tajamulkhann
30. Python 2 vs Python 3?
Python 2 Python 3
5 / 2 → 2 (integer division
Division 5 / 2 → 2.5 (true division)
by default)
n n
a
Strings ASCII by default Unicode by default
l k
xrange() for efficiency, h
range() is memory-efficient
u
xrange/range
range() returns list (like xrange())
ja m
a
Exceptions except Exception, e: syntax except Exception as e: required
@ T
input()
input() evaluates input as
input() returns a string
code
@Tajamulkhann
31. List Comprehensions in Python.
List comprehensions provide a concise way to
create lists based on existing lists or iterables.
[expression for item in iterable if condition]
Key features:
n n
a
More readable and often faster than
h
equivalent for loops
u l k
Can include conditions with 'if'
ja m
Can use multiple 'for' statements for nested
T a
iterations
@ Create a new list without modifying the
original Similar syntax works for dict/set
comprehensions
Example:
squares = [x*x for x in range(10) if x % 2 == 0]
@Tajamulkhann
32. Difference between is and ==
'is' operator:
Checks for identity (if two variables point to
same object in memory)
Compares the memory addresses of objects
n
Returns True if both variables refer to exactly
n
the same object
h a
l k
Used for singletons like None: if x is None
u
'==' operator:
ja m
T a
Check for equality (if 2 objects have same
@
value)
Calls the __eq__() method
Can be overridden in custom classes
Compares the content/value of objects
Example:
[] == [] returns True, but [] is [] returns False
@Tajamulkhann
33. Exception Handling
Exceptions in Python are errors that occur
during program execution.
n
to catch and manage errors without stopping
n
the program.
h a
l k
try: Code that may cause an error
u
except: Code to handle the error
ja m
finally: Code that runs regardless of errors
T
Example a
@
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
@Tajamulkhann
34. Concept of Virtual environments.
Virtual environments are isolated setups that:
Let projects use different dependencies
Prevent version conflicts
Keep the global Python clean
Enable reproducible development
n n
h a
Tools:
venv, virtualenv, condau l k
ja m
T a
Basic usage:
@
python -m venv myenv # Create source
myenv/bin/activate # Activate (Unix)
myenv\Scripts\activate # Activate (Windows)
pip install package # Install packages
deactivate # Exit
@Tajamulkhann
35. Monkey Patching
It means changing code (functions, methods,
classes) at runtime without modifying the
source.
Used for:
Extending third-party libraries
n n
Fixing bugs in external code
h a
Mocking in tests
u l
Debugging or profiling
k
Risks:
ja m
T a
Can make code fragile and hard to maintain.
@
Example:
def original():
return 1
@Tajamulkhann
36. import statement
Import Statement: Loads modules/packages
into the current namespace.
How it works:
1.Looks in sys.path
2.Checks sys.modules cache
n n
a
3.Creates module if not cached
h
l
4.Executes module code
u
5.Stores in sys.modules
k
ja m
6.Binds to local name
T a
Variations:
@ import module
from module import name
import module as alias
from module import name as alias
from module import * (not recommended)
@Tajamulkhann
37. Decorator in python.
A decorator is a function that takes another
function and extends or modifies its behavior
without changing its code. It “wraps” the
original function.
Example:
n n
def my_decorator(func):
h a
def wrapper():
u l k
print("Before function call")
func()
ja m
T a
print("After function call")
@return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
@Tajamulkhann
38. Functional programming Concept
Functional programming in Python focuses on:
Immutable data (no state changes)
Pure functions (consistent outputs, no side
effects)
n
First-class functions (functions as values)
n
a
Higher-order functions (take/return
h
functions)
u l k
Function composition (combine simple
functions)
ja m
T a
@
Python tools include:
map(), filter(), reduce(), lambdas, list
comprehensions, decorators, and modules like
functools and itertools.
@Tajamulkhann
39. Python Functional Utilities
map(function, iterable) Applies function to
each item in iterable and returns a map object
of results.
filter(function, iterable) Returns items from
iterable where function(item) is True.
n n
a
reduce(function, iterable) (from functools)
h
l k
Applies function cumulatively to items of
u
iterable, reducing it to a single value.
ja m
Example:
T a
@
from functools import reduce
nums = [1, 2, 3, 4, 5]
map square each number
squares = list(map(lambda x: x**2, nums))
filter keep even numbers
evens = list(filter(lambda x: x % 2 == 0, nums))
reduce sum all numbers
total = reduce(lambda x, y: x + y, nums)
@Tajamulkhann
40. Generator Expressions
resemble list comprehensions but produce
generators instead of lists
(expression for item in iterable if condition)
Key points:
Use parentheses () instead of square
n n
brackets []
h a
l k
Evaluate lazily, generating items on-
demand u
ja m
More memory-efficient, ideal for large data
T
sets a
@ Can be iterated only once
Perfect for streaming data or saving
memory
Can be passed directly to functions
Example
sum(x*x for x in range(1, 10))
@Tajamulkhann
41. append() and extend() in Python?
"append():
- Adds a single element to the end of a list
- The argument becomes one new element
regardless of its type
n
- If you append a list, it becomes a nested list
n
a
- Example: lst.append(5) → [1, 2, 3, 4, 5]
h
7]] u l k
- Example: lst.append([6, 7]) → [1, 2, 3, 4, 5, [6,
ja m
T
extend():a
@
- Adds multiple elements to the end of a list
- Takes an iterable and adds each element
individually
- No nested lists are created
- Example: lst.extend([6, 7]) → [1, 2, 3, 4, 5, 6, 7]
- Equivalent to: lst += [6, 7]
@Tajamulkhann
42. pickling and unpickling in Python.
Pickling:
Converts Python objects to byte streams for
storage or transfer using the pickle module.
pickle.dump(obj, file) → to file
pickle.dumps(obj) → to bytes
n n
h a
Unpickling:
u l k
Restores objects from byte streams.
ja m
pickle.load(file)
T a
pickle.loads(bytes)
@
Use cases: Save state, cache results, inter-
process communication.
Note: Avoid unpickling untrusted data (security
risk).
@Tajamulkhann
43. docstrings and its used?
Docstrings are triple-quoted string literals
placed at the start of a module, class, or
function to describe its purpose.
Used for documentation, accessible via .
__doc__ or help()
n n
Follow PEP 257 conventions
h a
l k
Parsed by tools like Sphinx for auto-
generating docs u
ja m
T
Example:a
@
def add(a, b):
"""Return the sum of a and b."""
return a + b
@Tajamulkhann
44. What are Type Hints?
Type hints (PEP 484) are optional annotations
that specify expected variable or function
types.
Don’t affect runtime; used for static analysis
and IDE support
n n
a
Improve readability and catch type errors
h
early (e.g., with mypy)
u l k
Introduced in Python 3.5 via the typing
module
ja m
T a
@
Example:
from typing import List
def greet(name: str) -> str:
return f"Hello, {name}"
x: int = 5
values: List[int] = [1, 2, 3]
@Tajamulkhann
45. range() vs enumerate()?
range() enumerate()
n n
When you need numeric
h a
When you need index and
Use Case
iteration
Returns
ja m
A range object (lazy An enumerate object
@Tajamulkhann
46. Tests in Python
Description Example
n
Built-in testing TestAdd(unittest.TestCase):
unittest
framework
n
def test_add(self):
a
self.assertEqual(add(2, 3), 5)
Popular 3rd-party
l k h
def test_add(): assert add(2,
pytest framework (simpler
m syntax) u 3) == 5
Method
a ja Description Example
@ T
def add(a, b): # add.py
return a + b
from add import add. # test_add.py
def test_add():
assert add(2, 3) == 5
pytest test_add.py # Run with:
@Tajamulkhann
47. File Handling
Open file: open(filename, mode)
Modes: 'r' (read), 'w' (write), 'a' (append), 'b'
(binary), 'x' (create)
Read: read(), readline(), readlines()
Write: write(), writelines()
n n
Close: close() or use with for automatic closing
h a
Example
u l k
ja m
with open('file.txt', 'w') as f:
f.write("Hello, world!\n")
T a
with open('file.txt', 'r') as f:
@content = f.read()
print(content)
@Tajamulkhann
48. Logging in python
Logging is a built-in module used to track
events during program execution. It helps
record information, warnings, errors, and
debugging messages to files or consoles.
@Tajamulkhann
49. Pseudocode
Pseudocode is not actual code, but rather a
simplified, high-level outline of a program's
logic in plain language
It is often written before actual code
Pseudocode
n n
START
h a
l k
Define number1 and number2
Set number1 to 5 u
ja m
Set number2 to 3
T a
Add number1 & number2 & store result in sum
@
Print sum END
Actual Code
number1 = 5
number2 = 3
sum = number1 + number2
print(sum)
@Tajamulkhann
50. Data Structures in Python
List ordered, mutable sequence
Tuple ordered, immutable sequence
Dictionary key-value mapping
Set unordered unique elements
Stack usually via list (append/pop)
n n
a
Queue usually via collections.deque
h
l k
Linked List singly or doubly linked nodes
u
Tree binary trees, BSTs, AVL trees, etc.
ja m
Graph nodes & edges representing
T a
networks
@Heap/Priority Queue specialized tree
structure for priority operations
Trie (Prefix Tree) efficient string prefix
retrieval
Disjoint Set / Union-Find set partitioning
Skip List probabilistic data structure for
ordered data
@Tajamulkhann
Follow for more!