Python Interview Questions & Answers

Top frequently asked interview questions with detailed answers, code examples, and expert tips.

105 Questions All Difficulty Levels Updated Mar 2026
1

What is Python? Easy

Python is a high-level, interpreted, dynamically typed programming language known for its simplicity and readability. It supports multiple paradigms including object-oriented, procedural, and functional programming.
basics introduction
2

What are Python data types? Easy

Python has built-in data types such as int, float, str, list, tuple, set, dict, and bool. It also supports custom data types using classes.
basics datatypes
3

What is the difference between list and tuple? Easy

Lists are mutable (can be changed), while tuples are immutable (cannot be changed). Tuples are faster and more memory-efficient.
collections list tuple
4

What is a dictionary in Python? Easy

A dictionary is a collection of key-value pairs. It is unordered, mutable, and indexed by keys.
dictionary collections
5

What are functions in Python? Easy

Functions are reusable blocks of code defined using the def keyword. They help organize and reuse logic.
functions
6

What is lambda function? Easy

A lambda function is an anonymous function defined using the lambda keyword. It is used for short, single-expression functions.
lambda functions
7

Explain OOP in Python. Medium

Object-Oriented Programming in Python includes concepts like class, object, inheritance, polymorphism, encapsulation, and abstraction.
oop classes
8

What is inheritance? Medium

Inheritance allows one class (child) to inherit properties and methods from another class (parent). It promotes code reusability.
oop inheritance
9

What is polymorphism? Medium

Polymorphism allows methods to have the same name but behave differently based on context.
oop polymorphism
10

What are decorators? Medium

Decorators are functions that modify the behavior of other functions or methods without changing their code.
decorators advanced
11

What are generators? Medium

Generators are functions that use the yield keyword to return values one at a time, making them memory efficient.
generators advanced
12

What is the difference between deep copy and shallow copy? Medium

Shallow copy copies references of objects, while deep copy copies the complete object including nested objects.
memory copy
13

What is GIL in Python? Hard

GIL (Global Interpreter Lock) ensures that only one thread executes Python bytecode at a time. It affects multi-threaded CPU-bound programs.
gil threading
14

What is multithreading? Medium

Multithreading allows concurrent execution of multiple threads within a program. It is useful for I/O-bound tasks.
threading concurrency
15

What is multiprocessing? Hard

Multiprocessing uses multiple CPU cores to execute tasks in parallel. It bypasses GIL and is used for CPU-bound tasks.
multiprocessing concurrency
16

What is exception handling? Easy

Exception handling uses try, except, finally blocks to manage runtime errors gracefully.
exceptions error-handling
17

What is virtual environment? Medium

A virtual environment allows you to create isolated Python environments to manage dependencies separately.
venv tools
18

What is PIP? Easy

PIP is Python package installer used to install and manage third-party libraries.
pip tools
19

What is Django? Medium

Django is a high-level Python web framework that follows the MVT architecture and helps build secure web applications.
django web
20

What is Flask? Medium

Flask is a lightweight Python web framework used for building simple web applications and APIs.
flask web
21

What is REST API? Medium

REST API is an architectural style for designing networked applications using HTTP methods like GET, POST, PUT, DELETE.
api rest
22

What is list comprehension? Easy

List comprehension is a concise way to create lists using a single line of code.
list-comprehension
23

What is the difference between Python 2 and Python 3? Medium

Python 3 has improved syntax, better Unicode support, and print is a function. Python 2 is deprecated.
python2 python3
24

How does Python manage memory? Hard

Python uses reference counting and garbage collection to manage memory automatically.
memory advanced
25

What is __init__ method? Easy

__init__ is a constructor method automatically called when a class object is created.
oop constructor
26

What is the Global Interpreter Lock (GIL)? Hard

GIL is a mutex that ensures only one thread executes Python bytecode at a time. It prevents true parallel execution of threads in CPython.
gil threading internals
27

How does Python memory management work? Hard

Python uses reference counting and a cyclic garbage collector to manage memory automatically.
memory garbage-collection
28

What is metaclass in Python? Hard

A metaclass defines how a class behaves. It is a class of a class and controls class creation.
metaclass oop
29

What are descriptors in Python? Hard

Descriptors are objects that define how attribute access is interpreted using __get__, __set__, and __delete__ methods.
descriptors advanced
30

Explain MRO (Method Resolution Order). Hard

MRO defines the order in which base classes are searched when executing a method.
mro oop
31

What is monkey patching? Hard

Monkey patching modifies classes or modules at runtime dynamically.
runtime advanced
32

What are coroutines? Hard

Coroutines are special functions defined with async and await that allow asynchronous programming.
async coroutines
33

Difference between async and threading? Hard

Async is single-threaded concurrency using event loop, threading uses multiple threads.
async threading
34

What is asyncio? Hard

Asyncio is Python library to write concurrent code using async/await syntax.
asyncio concurrency
35

What is context manager? Hard

Context managers manage resources using with statement and implement __enter__ and __exit__.
context-manager advanced
36

Explain deep vs shallow copy. Hard

Shallow copy copies references, deep copy copies entire nested structure.
memory copy
37

What is __slots__? Hard

__slots__ restricts dynamic attribute creation and reduces memory usage.
memory optimization
38

Explain Python bytecode. Hard

Python compiles code into bytecode which runs on Python Virtual Machine.
bytecode internals
39

What is Python Virtual Machine? Hard

PVM executes compiled bytecode and handles memory management.
pvm internals
40

Explain difference between multiprocessing and threading. Hard

Multiprocessing uses multiple CPU cores, threading shares memory but limited by GIL.
multiprocessing threading
41

What is pickling? Hard

Pickling converts Python object into byte stream for storage or transfer.
serialization pickle
42

What is GIL limitation workaround? Hard

Use multiprocessing or C extensions to bypass GIL limitations.
gil performance
43

What is dynamic typing? Hard

Python determines variable type at runtime.
typing dynamic
44

Explain static typing in Python. Hard

Static typing can be implemented using type hints and mypy.
typing type-hints
45

What is Cython? Hard

Cython is superset of Python that compiles to C for performance.
cython performance
46

What are decorators with arguments? Hard

Decorators can accept parameters and return nested wrapper functions.
decorators advanced
47

Explain closures in Python. Hard

Closure is inner function that remembers variables from enclosing scope.
closures functions
48

What is partial function? Hard

functools.partial creates new function with pre-filled arguments.
functional advanced
49

Explain Python import system. Hard

Python uses sys.path and module cache to locate and load modules.
import modules
50

What is memory leak in Python? Hard

Occurs when objects are referenced but not released properly.
memory advanced
51

Explain weak references. Hard

Weak references allow object to be garbage collected.
weakref memory
52

What is Python GIL impact on CPU tasks? Hard

CPU-bound tasks do not scale with threads due to GIL.
gil cpu-bound
53

Explain __new__ vs __init__. Hard

__new__ creates instance, __init__ initializes it.
oop constructor
54

What is dataclass? Hard

Dataclass auto-generates boilerplate code like __init__, __repr__.
dataclass advanced
55

Explain Abstract Base Classes. Hard

ABC enforces method implementation in subclasses.
abc oop
56

What is dependency injection? Hard

Technique where dependencies are provided externally.
design-pattern
57

Explain Python GIL removal proposals. Hard

Alternative interpreters like Jython and IronPython do not use GIL.
gil internals
58

What is lru_cache? Hard

functools.lru_cache caches function results for performance.
caching performance
59

Explain Python packaging. Hard

Uses setup.py or pyproject.toml to distribute packages.
packaging devops
60

What is event loop? Hard

Event loop schedules async tasks and callbacks.
async event-loop
61

Explain thread safety. Hard

Thread safety ensures shared resources are accessed properly.
threading safety
62

What is race condition? Hard

Race condition occurs when threads access shared resource unsafely.
threading concurrency
63

Explain GIL vs Jython. Hard

Jython does not use GIL because it runs on JVM.
gil jython
64

What is memory profiling? Hard

Memory profiling analyzes memory usage in applications.
profiling performance
65

Explain Python interpreter types. Hard

CPython, PyPy, Jython, IronPython are Python implementations.
interpreter advanced
66

What is Python AST? Hard

AST (Abstract Syntax Tree) represents parsed Python code.
ast internals
67

Explain concurrency vs parallelism. Hard

Concurrency is managing tasks, parallelism is executing tasks simultaneously.
concurrency parallelism
68

What is greenlet? Hard

Greenlet enables lightweight coroutine-based concurrency.
greenlet async
69

Explain Python memory model. Hard

Python memory model handles stack, heap and reference counting.
memory internals
70

What is contextvars? Hard

contextvars provides context-local state for async tasks.
async contextvars
71

Explain Python threading limitations. Hard

Threads share memory but limited by GIL.
threading gil
72

What is type hinting? Hard

Type hints provide optional static typing information.
typing type-hints
73

Explain Python optimization techniques. Hard

Use caching, multiprocessing, C extensions, profiling tools.
optimization performance
74

How to improve Python performance? Hard

Use PyPy, optimize algorithms, reduce object creation.
performance advanced
75

Explain Python security best practices. Hard

Use virtual environments, sanitize inputs, avoid eval.
security best-practices
76

Design a rate limiter in Python. Hard

Use a token bucket or sliding window approach. Store timestamps in a queue and allow requests within time window.
rate-limiter system-design
77

Build an LRU Cache from scratch. Hard

Use OrderedDict or implement doubly linked list with hashmap for O(1) operations.
lru-cache data-structures
78

Implement a thread-safe counter. Medium

Use threading.Lock() to synchronize increments.
threading concurrency
79

Create a retry decorator for API calls. Medium

Use decorator with loop and exception handling to retry function execution.
decorator error-handling
80

Design a URL shortener service. Hard

Generate unique hash, store mapping in DB, redirect using lookup.
system-design hashing
81

Write a program to detect memory leak. Hard

Use tracemalloc or memory_profiler to monitor object allocation.
memory profiling
82

Implement producer-consumer problem. Hard

Use queue.Queue with threading or multiprocessing.
concurrency queue
83

Design a logging system. Medium

Use logging module with different handlers and log levels.
logging design
84

Build a file upload validator. Medium

Check file type, size and sanitize filename before saving.
file-handling security
85

Implement pagination in API. Medium

Use limit and offset parameters in database queries.
api backend
86

Write a Python script to scrape website data. Medium

Use requests and BeautifulSoup libraries.
web-scraping automation
87

Design a background job queue. Hard

Use Redis with Celery or Bull-like system.
queue background-jobs
88

Implement custom context manager. Medium

Define class with __enter__ and __exit__ methods.
context-manager advanced
89

Design a chat application backend. Hard

Use WebSockets and event-driven architecture.
websocket system-design
90

Implement authentication using JWT. Medium

Generate token after login and validate on each request.
jwt authentication
91

Build a REST API with input validation. Medium

Use FastAPI or Flask with Pydantic or Marshmallow.
rest-api validation
92

Design a caching layer. Hard

Use Redis or in-memory caching with expiration.
caching performance
93

Implement exponential backoff strategy. Medium

Retry with increasing delay using time.sleep.
retry error-handling
94

Write a function to merge overlapping intervals. Medium

Sort intervals and merge if overlapping.
algorithms arrays
95

Implement custom iterator. Medium

Define __iter__ and __next__ methods.
iterator advanced
96

Design a task scheduler. Hard

Use cron-like scheduling or APScheduler.
scheduler design
97

Implement multi-threaded file downloader. Hard

Use threading or concurrent.futures module.
multithreading io
98

Create a CLI tool in Python. Medium

Use argparse module to parse command-line arguments.
cli tools
99

Design a notification system. Hard

Use pub-sub pattern and message broker.
system-design pubsub
100

Write a Python script for log parsing. Medium

Read file line by line and use regex to extract data.
regex file-handling
101

Implement role-based access control. Hard

Store roles and check permissions before action.
authorization security
102

Design a payment processing module. Hard

Handle transaction states, retries and idempotency.
payments system-design
103

Build a concurrent web crawler. Hard

Use asyncio and aiohttp for async crawling.
asyncio web-crawler
104

Implement circuit breaker pattern. Hard

Stop calls to failing service after threshold.
design-pattern resilience
105

Design a distributed cache invalidation strategy. Hard

Use versioning or pub-sub to invalidate across nodes.
distributed-system caching
📊 Questions Breakdown
🟢 Easy 10
🟡 Medium 26
🔴 Hard 69
🎓 Master Python Training

Join our live classes with expert instructors and hands-on projects.

Enroll Now

What People Say

Testimonial

Nagmani Solanki

Digital Marketing

Edugators platform is the best place to learn live classes, and live projects by which you can understand easily and have excellent customer service.

Testimonial

Saurabh Arya

Full Stack Developer

It was a very good experience. Edugators and the instructor worked with us through the whole process to ensure we received the best training solution for our needs.

testimonial

Praveen Madhukar

Web Design

I would definitely recommend taking courses from Edugators. The instructors are very knowledgeable, receptive to questions and willing to go out of the way to help you.

Need To Train Your Corporate Team ?

Customized Corporate Training Programs and Developing Skills For Project Success.

Google AdWords Training
React Training
Angular Training
Node.js Training
AWS Training
DevOps Training
Python Training
Hadoop Training
Photoshop Training
CorelDraw Training
.NET Training

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators