HomeInterview QuestionsPython Interview QuestionsTop 20
🐍
Free Study Guide · 2025

Top 20 PythonInterview Questions & Answers (2025)

Python dominates data science, backend development, and automation roles in India. These questions are asked at startups, product companies, and in data engineering interviews at companies like Flipkart, PhonePe, Razorpay, and every data-heavy startup.

20 questions
Detailed answers
100% free
Also available:Top 10All 20 questions →
1What is Python and what makes it popular?
Python is a high-level, interpreted, dynamically-typed language known for its readable syntax. Its popularity comes from: a vast standard library and ecosystem (NumPy, Pandas, Django, Flask), strong community, versatility across web development, data science, ML, automation, and scripting, and the fact that it reads almost like plain English, lowering the learning curve.
2What are Python decorators?
A decorator is a function that wraps another function to extend its behaviour without modifying it. The @decorator syntax is shorthand for func = decorator(func). Common uses: logging, authentication checks (@login_required in Django), caching (@functools.lru_cache), rate limiting, and timing function execution. Decorators are a powerful application of Python's first-class functions and closures.
3What is the difference between a list, tuple, and set?
Lists are ordered, mutable, and allow duplicates — use for sequences you'll modify. Tuples are ordered, immutable, and allow duplicates — use for fixed records, dict keys, or when you want to signal that data shouldn't change. Sets are unordered, mutable, and contain no duplicates — use for membership tests (O(1) lookup), deduplication, and set operations (union, intersection).
4What is a generator in Python?
A generator is a function that uses yield instead of return to produce a sequence of values lazily — one at a time, on demand. Calling a generator function returns a generator object; values are computed only when iterated. This makes generators memory-efficient for large datasets. Generator expressions ((x*2 for x in range(n))) are like lazy list comprehensions.
5What is the GIL (Global Interpreter Lock)?
The GIL is a mutex in CPython that allows only one thread to execute Python bytecode at a time, even on multi-core systems. This means Python threads don't truly run in parallel for CPU-bound work. Workarounds: use multiprocessing (separate processes, each with their own GIL) for CPU-bound tasks, or use async/await (asyncio) for I/O-bound concurrency. NumPy operations release the GIL.
6What are list comprehensions?
List comprehensions provide a concise way to create lists: [expression for item in iterable if condition]. They are faster than equivalent for loops (optimised in CPython) and more readable. dict comprehensions ({k: v for k, v in items}), set comprehensions ({x for x in iterable}), and generator expressions ((x for x in iterable)) follow the same syntax.
7What is the difference between *args and **kwargs?
*args collects additional positional arguments into a tuple. **kwargs collects additional keyword arguments into a dictionary. They let functions accept variable numbers of arguments. The names args and kwargs are conventions — the * and ** are the actual syntax. Order in function signatures must be: positional, *args, keyword-only, **kwargs.
8What are Python's data model (dunder/magic) methods?
Dunder methods (__init__, __str__, __repr__, __len__, __getitem__, __eq__, __lt__, etc.) define how objects interact with Python's built-in operations. __init__ is the constructor. __str__ defines str(obj). __repr__ defines repr(obj) for debugging. __len__ enables len(obj). __getitem__ enables obj[key]. Implementing these makes your classes feel like native Python types.
9What is the difference between deep copy and shallow copy?
A shallow copy (copy.copy()) creates a new object but inserts references to the original's nested objects — mutating a nested list in the copy affects the original. A deep copy (copy.deepcopy()) recursively copies all nested objects, creating fully independent duplicates. For simple objects with no nesting, both behave the same.
10What is a Python context manager and the 'with' statement?
A context manager handles setup and teardown automatically. The with statement calls __enter__ on entry and __exit__ on exit (even if an exception occurs). The most common use is file handling: with open('file') as f — the file is guaranteed to close after the block. You can create custom context managers using the contextlib.contextmanager decorator.
11What is the difference between is and ==?
== compares values (calls __eq__). is compares identity — whether two variables point to the exact same object in memory. is is appropriate for comparing with None (use x is None, not x == None), True, and False. CPython caches small integers (-5 to 256) and interned strings, so is may return True for these unexpectedly — never rely on is for value comparison.
12What is Python's MRO (Method Resolution Order)?
MRO is the order Python uses to look up methods in a class hierarchy with multiple inheritance. Python uses the C3 linearization algorithm. You can inspect it with ClassName.__mro__ or ClassName.mro(). The super() function follows MRO, enabling cooperative multiple inheritance. Understanding MRO prevents the diamond problem where the same method exists in multiple parent classes.
13What is the difference between a module and a package?
A module is a single .py file that can be imported. A package is a directory with an __init__.py file (can be empty) that groups related modules. Packages can be nested. __init__.py runs when the package is first imported and can expose a simplified API. Modern Python (3.3+) also supports namespace packages without __init__.py.
14What are lambda functions in Python?
Lambda functions are anonymous, single-expression functions: lambda x, y: x + y. They're syntactically restricted to one expression and return it implicitly. Use them for short callbacks passed to map(), filter(), sorted(key=...), or any function expecting a callable. For anything more complex, a named function is more readable and testable.
15How does Python handle memory management?
Python uses reference counting as its primary memory management mechanism — an object is deallocated when its reference count drops to zero. A cyclic garbage collector handles reference cycles (e.g., a references b, b references a). The gc module exposes this collector. Python also uses memory pools (pymalloc) for small objects to reduce fragmentation and allocation overhead.
16What is the difference between @staticmethod and @classmethod?
@staticmethod defines a method that belongs to the class but receives neither the instance (self) nor the class (cls) as the first argument — it's essentially a namespaced plain function. @classmethod receives the class as the first argument (cls) and can access/modify class state. @classmethod is commonly used as alternative constructors (e.g., Date.from_string()).
17What is virtualenv and why do you use it?
Virtualenv (or venv in Python 3) creates isolated Python environments with their own installed packages, preventing dependency conflicts between projects. Each project gets its own copy of pip-installed libraries. Best practice: always create a virtual environment per project, commit requirements.txt (generated with pip freeze), and never install project dependencies globally.
18What are Python's built-in data structures?
Python's core data structures: list (ordered, mutable sequence), tuple (ordered, immutable), set (unordered, unique items), frozenset (immutable set), dict (key-value mapping), and collections module extras: deque (double-ended queue), Counter, defaultdict, OrderedDict, and namedtuple. Choosing the right structure — based on access patterns — is key to writing efficient Python.
19What is asyncio and when would you use it?
asyncio is Python's standard library for writing concurrent code using the async/await syntax and an event loop. It's ideal for I/O-bound operations (network calls, file reads, database queries) where threads spend most time waiting. async def defines a coroutine; await pauses it while waiting for another coroutine. Use asyncio + httpx/aiohttp for high-throughput async HTTP clients and servers.
20What is the difference between Django and Flask?
Django is a batteries-included framework with a built-in ORM, admin panel, authentication, URL routing, forms, and templates — best for large applications with complex data models. Flask is a minimal microframework giving you just routing and request handling — you pick your own ORM, auth library, and templates. Django provides structure; Flask provides flexibility.
Level up your prep
Get company-specific Python questions
Upload your resume → get questions tailored to Google, Amazon, TCS, and 50+ companies.
Try AI Interview Prep →
© 2025 CareerLens · Home · Interview Questions · Pricing