0% found this document useful (0 votes)
4 views29 pages

Advanced Python Job Interview Questions Answers

This document contains a comprehensive list of advanced Python interview questions and answers covering various topics such as decorators, memory management, GIL, multithreading, generators, context managers, and more. It also includes practical coding interview questions and system design considerations. The content is structured to aid candidates in preparing for technical interviews by providing essential concepts and examples.

Uploaded by

goswamirohit825
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views29 pages

Advanced Python Job Interview Questions Answers

This document contains a comprehensive list of advanced Python interview questions and answers covering various topics such as decorators, memory management, GIL, multithreading, generators, context managers, and more. It also includes practical coding interview questions and system design considerations. The content is structured to aid candidates in preparing for technical interviews by providing essential concepts and examples.

Uploaded by

goswamirohit825
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Advanced Python Interview Questions and

Answers for Job Interviews


1. What are Python decorators?
A decorator is a function that modifies the behavior of another function or class without changing its
source code. Decorators use the @decorator_name syntax.

from functools import wraps

def logger(func):
@wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__}")
return func(*args, **kwargs)
return wrapper

@logger
def add(a, b):
return a + b

Key Points

• Functions are first-class objects.


• Used for logging, authentication, caching, retries, etc.
• [Link] preserves metadata.

2. What is the difference between deep copy and shallow copy?

Shallow Copy

Copies only the outer object. Nested objects are shared.

import copy

a = [[1, 2], [3, 4]]


b = [Link](a)

Deep Copy

Copies recursively.

1
c = [Link](a)

Difference

• Shallow copy references nested objects.


• Deep copy creates independent nested objects.

3. What are args and *kwargs?

*args

Accepts variable positional arguments.

def total(*args):
return sum(args)

**kwargs

Accepts variable keyword arguments.

def display(**kwargs):
print(kwargs)

Usage

Useful for flexible APIs and wrapper functions.

4. Explain Python memory management.


Python uses:

• Reference counting
• Garbage collection
• Private heap memory

Garbage Collector

Handles cyclic references.

import gc
[Link]()

2
Important Concepts

• Stack memory stores references.


• Heap stores objects.
• del decreases reference count.

5. What is GIL in Python?


GIL stands for Global Interpreter Lock.

It allows only one thread to execute Python bytecode at a time in CPython.

Implications

• Multithreading is not efficient for CPU-bound tasks.


• Useful for I/O-bound tasks.

Alternatives

• Multiprocessing
• Asyncio
• Jython / IronPython

6. Difference between multithreading and multiprocessing.

Feature Multithreading Multiprocessing

Memory Shared Separate

Speed Better for I/O Better for CPU

GIL Impact Yes No

Communication Easier More complex

Example

from multiprocessing import Process

7. What are generators?


Generators produce values lazily using yield .

3
def numbers():
for i in range(5):
yield i

Advantages

• Memory efficient
• Useful for large datasets
• Supports iteration pipelines

8. Difference between iterator and iterable.

Iterable

Object that can return an iterator.

Iterator

Object with:

• __iter__()
• __next__()

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

9. Explain Python context managers.


Context managers manage resources automatically.

with open("[Link]") as f:
data = [Link]()

Custom Context Manager

class Demo:
def __enter__(self):
print("Start")

def __exit__(self, exc_type, exc_val, exc_tb):


print("End")

4
10. What is monkey patching?
Dynamic modification of classes/modules at runtime.

class A:
pass

A.new_method = lambda self: "Hello"

Use Cases

• Testing
• Extending libraries

Risks

• Hard debugging
• Unexpected behavior

11. Explain method resolution order (MRO).


MRO defines the order in which parent classes are searched.

class A: pass
class B(A): pass
class C(A): pass
class D(B, C): pass

print([Link]())

Python uses C3 linearization.

12. What are metaclasses?


Metaclasses define how classes behave.

Simplified Idea

• Class creates objects.


• Metaclass creates classes.

class Meta(type):
pass

5
class MyClass(metaclass=Meta):
pass

Use Cases

• ORMs
• Framework internals
• API validation

13. Explain duck typing.


Python focuses on behavior rather than type.

"If it walks like a duck and quacks like a duck, it is a duck."

class Dog:
def speak(self):
return "Bark"

If an object has the required method, it works.

14. Difference between is and ==.

Operator Meaning

== Value equality

is Identity equality

a = [1]
b = [1]

print(a == b)
print(a is b)

15. What are Python descriptors?


Descriptors customize attribute access using:

• __get__
• __set__
• __delete__

6
class Descriptor:
def __get__(self, instance, owner):
return "value"

Used internally by:

• properties
• methods
• classmethod
• staticmethod

16. Explain closures in Python.


A closure remembers variables from its enclosing scope.

def outer(x):
def inner(y):
return x + y
return inner

17. What is the difference between @staticmethod and


@classmethod?

Feature staticmethod classmethod

Receives class No Yes

First argument None cls

Access class state No Yes

class A:
@staticmethod
def s():
pass

@classmethod
def c(cls):
pass

7
18. What are Python data classes?
Data classes reduce boilerplate.

from dataclasses import dataclass

@dataclass
class User:
name: str
age: int

Automatically generates:

• __init__
• __repr__
• __eq__

19. Explain async and await.


Used for asynchronous programming.

import asyncio

async def hello():


await [Link](1)

Best For

• APIs
• Network calls
• High concurrency

20. Difference between concurrency and parallelism.

Concurrency Parallelism

Tasks overlap Tasks run simultaneously

Single core possible Multiple cores needed

Improves responsiveness Improves speed

8
21. What is memoization?
Caching function results.

from functools import lru_cache

@lru_cache

def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)

22. Explain list comprehension.


Compact syntax for creating lists.

squares = [x*x for x in range(5)]

Benefits

• Readable
• Faster than loops

23. What is the difference between Python lists and tuples?

List Tuple

Mutable Immutable

Slower Faster

More memory Less memory

Use tuples for fixed data.

24. Explain Python packaging.


Packaging structures reusable Python projects.

Common Tools

• pip
• setuptools

9
• poetry
• virtualenv

Important Files

• [Link]
• [Link]
• [Link]

25. What are virtual environments?


Virtual environments isolate dependencies.

python -m venv env

Benefits

• Dependency isolation
• Prevent version conflicts

26. Explain Python’s LEGB rule.


Variable lookup order: 1. Local 2. Enclosing 3. Global 4. Built-in

x = 10

Python searches scopes in this order.

27. Difference between mutable and immutable objects.

Mutable

Can change after creation. Examples:

• list
• dict
• set

Immutable

Cannot change. Examples:

• tuple
• string

10
• int

28. Explain Python hashability.


Hashable objects:

• Have fixed hash value


• Can be dictionary keys

Immutable objects are usually hashable.

hash("abc")

29. What is slots?


__slots__ reduces memory usage.

class A:
__slots__ = ['name']

Benefits

• Faster attribute access


• Less memory

Limitation

No dynamic attributes.

30. Explain Python comprehensions.

Types

• List comprehension
• Dict comprehension
• Set comprehension
• Generator expression

{x: x*x for x in range(5)}

11
31. What are coroutines?
Coroutines are special functions that can pause and resume.

Implemented using:

• async
• await

Useful for asynchronous workflows.

32. Explain monkey patching vs inheritance.

Monkey Patching Inheritance

Runtime modification Extend using subclass

Riskier Safer

Dynamic Structured

33. What is dependency injection?


Dependencies are provided externally.

class Service:
def __init__(self, db):
[Link] = db

Benefits

• Testability
• Loose coupling

34. Explain Python’s garbage collection generations.


Python divides objects into generations:

• Generation 0
• Generation 1
• Generation 2

Long-lived objects are checked less frequently.

12
35. What are weak references?
Weak references do not increase reference count.

import weakref

Useful for:

• Caches
• Memory-sensitive systems

36. Difference between threading, asyncio, and multiprocessing.

Technique Best For

Threading I/O-bound

Asyncio Massive I/O concurrency

Multiprocessing CPU-bound

37. Explain Python serialization.


Serialization converts objects into transferable format.

Common Modules

• pickle
• json

import pickle

Warning

Never unpickle untrusted data.

38. What is the difference between deepcopy and serialization?

deepcopy serialization

Copies in memory Converts format

Faster Useful for storage/network

13
39. Explain the Python import system.
Python searches modules in:

• Current directory
• PYTHONPATH
• Site-packages

Related Files

• __init__.py
• [Link]

40. What is circular import?


Two modules importing each other.

Solutions

• Move imports inside functions


• Refactor code
• Create common module

41. Explain Python property decorator.


Used for controlled attribute access.

class User:
def __init__(self):
self._age = 0

@property
def age(self):
return self._age

42. What are abstract base classes?


Used to enforce method implementation.

from abc import ABC, abstractmethod

class Shape(ABC):
@abstractmethod

14
def area(self):
pass

43. Explain singleton design pattern in Python.


Ensures one object instance.

class Singleton:
_instance = None

Used in:

• Logging
• Configuration managers

44. What are Python enums?


Enums define named constants.

from enum import Enum

class Color(Enum):
RED = 1

45. Explain Python type hints.


Type hints improve readability and tooling.

def add(a: int, b: int) -> int:


return a + b

Tools

• mypy
• pyright

46. What is monkey patching in testing?


Temporarily replacing functions during tests.

15
from [Link] import patch

Used heavily in unit testing.

47. Explain unit testing in Python.

Frameworks

• unittest
• pytest

def test_add():
assert add(2, 3) == 5

48. Explain Python logging.

import logging

[Link](level=[Link])
[Link]("Application started")

Levels

• DEBUG
• INFO
• WARNING
• ERROR
• CRITICAL

49. What is the difference between Flask and Django?

Flask Django

Lightweight Full framework

Flexible Batteries included

Microservices Large applications

50. Explain Python’s pass-by-object-reference.


Python passes references to objects.

16
Mutable objects can change inside functions.

def modify(lst):
[Link](10)

System Design + Python Interview Questions


51. How would you optimize a slow Python application?

Steps

1. Profile using cProfile


2. Reduce algorithm complexity
3. Use caching
4. Optimize database queries
5. Use async or multiprocessing
6. Use NumPy/Pandas for heavy computation

52. How would you design a scalable REST API in Python?

Components

• FastAPI/Django/Flask
• PostgreSQL
• Redis caching
• Celery for background jobs
• Docker + Kubernetes
• JWT authentication
• Rate limiting

53. Explain FastAPI advantages.

Advantages

• Async support
• Automatic OpenAPI docs
• High performance
• Pydantic validation
• Type hint integration

17
54. Difference between threading and async APIs.

Threading

• Uses threads
• More memory overhead

Async

• Event loop based


• Better for high concurrency

55. Explain Python ORM.


ORM maps objects to database tables.

Examples

• SQLAlchemy
• Django ORM

Benefits:

• Cleaner code
• Reduced SQL writing

56. What is SQLAlchemy session?


Session manages:

• Transactions
• Persistence
• Query execution

[Link](user)
[Link]()

57. Explain Python caching strategies.

Types

• In-memory cache
• Redis
• LRU cache
• CDN cache

18
Use Cases

• APIs
• Expensive computations

58. Explain Celery.


Celery handles asynchronous background tasks.

Components

• Broker (Redis/RabbitMQ)
• Workers
• Task queue

Used for:

• Email sending
• Notifications
• Report generation

59. What are race conditions?


Multiple threads/processes modifying shared data simultaneously.

Solutions

• Locks
• Queues
• Semaphores
• Atomic operations

60. Explain Python locks.

from threading import Lock

lock = Lock()

Used to synchronize shared resources.

19
Coding Interview Questions
61. Reverse a string.

s[::-1]

62. Check palindrome.

def is_palindrome(s):
return s == s[::-1]

63. Find duplicate elements.

from collections import Counter

nums = [1,2,2,3]
print([k for k,v in Counter(nums).items() if v > 1])

64. Merge two dictionaries.

c = {**a, **b}

65. Find frequency of words.

from collections import Counter


Counter([Link]())

66. Explain time complexity of dictionary operations.


Average complexity:

• Insert: O(1)
• Search: O(1)
• Delete: O(1)

20
Uses hash tables internally.

67. Explain Python set internals.


Sets use hash tables.

Operations

• Insert: O(1)
• Search: O(1)
• Union/intersection optimized

68. Difference between remove(), discard(), and pop() in sets.

Method Behavior

remove Error if missing

discard No error

pop Removes random element

69. What are lambda functions?


Anonymous functions.

square = lambda x: x*x

Useful with:

• map
• filter
• sorted

70. Explain map, filter, and reduce.

map

Transforms data.

filter

Filters data.

21
reduce

Aggregates data.

from functools import reduce

Python Interview Rapid Fire


71. Difference between append and extend.
• append() adds single object.
• extend() adds iterable elements.

72. Difference between sort and sorted.


• sort() modifies list.
• sorted() returns new list.

73. What is slicing?

arr[start:end:step]

74. What is unpacking?

a, b = [1, 2]

75. Explain zip function.


Combines iterables.

zip(a, b)

76. Explain enumerate.


Provides index and value.

22
for i, val in enumerate(arr):
pass

77. Explain any() and all().


• any() returns True if any value is True.
• all() returns True if all values are True.

78. What are f-strings?


Formatted string literals.

name = "Aishik"
print(f"Hello {name}")

79. Explain Python heapq.


Provides heap queue algorithms.

import heapq

Useful for:

• Priority queues
• Top-k problems

80. Explain deque.


Efficient double-ended queue.

from collections import deque

Fast append/pop from both ends.

23
HR + Practical Python Interview Questions
81. What Python projects have you built?
Prepare answers around:

• REST APIs
• Automation
• ML projects
• Web scraping
• Full-stack systems
• Data pipelines

82. Explain a difficult bug you solved.


Use STAR format:

• Situation
• Task
• Action
• Result

83. How do you improve Python code quality?

Techniques

• Type hints
• Linters
• Unit tests
• Code reviews
• CI/CD
• Profiling

84. How do you handle large datasets in Python?

Tools

• Pandas chunking
• Dask
• NumPy
• PySpark
• Generators

24
85. Explain API authentication methods.

Common Methods

• JWT
• OAuth2
• API keys
• Session auth

86. Explain JWT flow.


1. User logs in.
2. Server validates.
3. JWT generated.
4. Client sends token in headers.
5. Server verifies signature.

87. Explain Python exception hierarchy.


Base class:

BaseException

Important subclasses:

• Exception
• ValueError
• TypeError
• KeyError
• IndexError

88. Difference between errors and exceptions.

Errors Exceptions

Usually unrecoverable Can be handled

SyntaxError ValueError

25
89. Explain custom exceptions.

class CustomError(Exception):
pass

Useful for domain-specific handling.

90. What is Pythonic code?


Pythonic code is:

• Readable
• Concise
• Idiomatic
• Maintainable

Examples:

• List comprehensions
• Context managers
• Built-in functions

Advanced CPython/Internal Questions


91. What is bytecode?
Python source code compiles into bytecode ( .pyc ) executed by the Python Virtual Machine.

92. What is the Python Virtual Machine?


PVM executes Python bytecode.

93. Explain reference counting.


Every object tracks references. When count reaches zero, memory is freed.

94. Why are Python integers immutable?


Immutability improves:

• Safety

26
• Hashability
• Optimization

95. Explain string interning.


Python reuses immutable strings for memory optimization.

96. What is the difference between CPython, PyPy, and Jython?

Implementation Language

CPython C

PyPy RPython with JIT

Jython Java

97. Explain Python’s dynamic typing.


Variable types are determined at runtime.

x = 10
x = "hello"

98. Explain duck typing vs static typing.


Python focuses on behavior. Static typing focuses on declared types.

99. Explain composition vs inheritance.

Composition

"Has-a" relationship.

Inheritance

"Is-a" relationship.

Composition is usually preferred for flexibility.

27
100. What are the most important Python interview topics?

Must Prepare

• OOP
• Decorators
• Generators
• Asyncio
• Multithreading vs multiprocessing
• FastAPI/Django
• SQLAlchemy
• REST APIs
• Data structures
• Time complexity
• Testing
• Logging
• Caching
• Docker basics
• System design

Final Interview Tips


Technical Round
• Explain trade-offs.
• Think aloud.
• Mention complexity.
• Write clean code.
• Handle edge cases.

HR Round
• Explain projects clearly.
• Focus on impact.
• Show debugging and teamwork skills.

Common Mistakes
• Memorizing without understanding
• Ignoring complexity
• Weak project explanation
• Not knowing basics deeply

Best Preparation Strategy


1. Practice DSA in Python.
2. Build REST APIs.
3. Learn async programming.

28
4. Practice SQL.
5. Mock interviews.
6. Revise projects deeply.
7. Learn debugging and profiling.

29

You might also like