Python remains one of the most in-demand skills across Indian tech hiring, from campus placement drives at service companies to specialist rounds at product firms and startups. This guide collects the most frequently asked Python interview questions with clear, technically correct answers, short code examples, and the reasoning interviewers actually want to hear. Whether you are a fresher walking into your first placement round or an experienced engineer targeting a backend or data role, these Python interview questions will help you revise fast and answer with confidence.
How to use this guide
Skim the sections that match your level, read each answer out loud, and then close the page and try to reproduce the key points from memory. Interviewers reward understanding, not memorised definitions.
Python Basics (Freshers)
What is Python and what are its key features?
Python is a high-level, interpreted, dynamically typed, general-purpose programming language. Its key features are readability through significant indentation, dynamic typing, automatic memory management with garbage collection, a large standard library, and support for multiple paradigms including procedural, object-oriented, and functional programming. It is cross-platform and has a huge ecosystem for web, data science, automation, and machine learning.
Is Python compiled or interpreted?
Both, in stages. Python source code is first compiled to bytecode (the .pyc files you see in __pycache__), and that bytecode is then executed by the Python Virtual Machine (PVM). So developers experience it as an interpreted language, but there is an internal compilation step to bytecode.
What does the term "dynamically typed" mean in Python?
It means you do not declare variable types. The type is associated with the object at runtime, not with the variable name. A single variable can be bound to an integer and later to a string. Python is also strongly typed, so it will not silently coerce a string into an integer during arithmetic.
What is PEP 8?
PEP 8 is the official style guide for Python code. It covers naming conventions, indentation of 4 spaces, maximum line length, import ordering, and whitespace usage. Interviewers ask this to check whether you write clean, team-friendly code. Tools like flake8, black, and pylint help enforce it.
What is the difference between a list and a tuple?
A list is mutable and a tuple is immutable. Lists use square brackets and tuples use parentheses. Because tuples are immutable they can be used as dictionary keys and are slightly faster and more memory efficient. Use tuples for fixed collections such as coordinates and lists for data that changes.
What are Python's built-in data types?
The core built-in types are numeric (int, float, complex), sequence (str, list, tuple, range), mapping (dict), set (set, frozenset), boolean (bool), and NoneType. Interviewers often follow up by asking which are mutable and which are immutable.
What is the difference between is and ==?
== compares values for equality, while is compares identity, meaning whether two references point to the exact same object in memory. Two lists with the same contents are == but not is. Use is mainly for singletons like None.
a = [1, 2]
b = [1, 2]
print(a == b) # True
print(a is b) # False
What are *args and **kwargs?
*args lets a function accept any number of positional arguments as a tuple, and **kwargs accepts any number of keyword arguments as a dictionary. They are useful when you do not know in advance how many arguments will be passed.
def demo(*args, **kwargs):
print(args) # tuple
print(kwargs) # dict
demo(1, 2, name="Goodspace")
What is the difference between append() and extend()?
append() adds its argument as a single element at the end of the list, so appending a list nests it. extend() iterates over its argument and adds each element individually, flattening one level.
a = [1, 2]
a.append([3, 4]) # [1, 2, [3, 4]]
b = [1, 2]
b.extend([3, 4]) # [1, 2, 3, 4]
What is slicing in Python?
Slicing extracts a portion of a sequence using sequence[start:stop:step]. The start is inclusive and the stop is exclusive. A negative step reverses the sequence, so s[::-1] returns a reversed copy of s.
Data Types and Structures
How is memory managed for small integers and strings?
Python caches small integers from -5 to 256 and interns many short strings, so multiple variables holding the same small value may share one object. This is why a is b can be True for small integers but False for large ones. Never rely on this behaviour in real code.
What is the difference between a shallow copy and a deep copy?
A shallow copy creates a new outer object but keeps references to the same inner objects, so nested mutable elements are shared. A deep copy recursively copies everything, producing a fully independent object. Use copy.copy() and copy.deepcopy() respectively.
import copy
nested = [[1, 2], [3, 4]]
shallow = copy.copy(nested)
deep = copy.deepcopy(nested)
How do sets differ from lists and dictionaries?
A set is an unordered collection of unique, hashable elements with no indexing. It offers fast membership testing in roughly O(1) time. A dictionary stores key-value pairs, also with unique hashable keys. Lists are ordered and allow duplicates. Choosing the right one is a common design question.
Comparison: list vs tuple vs set vs dict
| Feature | list | tuple | set | dict |
|---|---|---|---|---|
| Syntax | [ ] |
( ) |
{ } |
{k: v} |
| Ordered | Yes | Yes | No (insertion order not guaranteed as index) | Yes (3.7+) |
| Mutable | Yes | No | Yes | Yes |
| Duplicates | Allowed | Allowed | Not allowed | Keys unique |
| Indexing | Yes | Yes | No | By key |
| Typical use | Dynamic sequence | Fixed record | Uniqueness, membership | Key-value lookup |
What is a dictionary comprehension?
It is a concise way to build a dictionary in a single expression, similar to list comprehensions.
squares = {n: n * n for n in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
How do you merge two dictionaries?
In Python 3.9 and later you can use the merge operator d1 | d2. Before that, {**d1, **d2} or d1.update(d2) were common. In all cases, keys in the second dictionary override duplicates from the first.
What are mutable and immutable objects, and why does it matter?
Immutable objects such as int, str, tuple, and frozenset cannot be changed after creation, while mutable ones such as list, dict, and set can. This matters for function arguments, since mutating a mutable argument inside a function affects the caller. It also determines what can be used as a dictionary key.
OOP in Python
What are the four pillars of OOP and how does Python support them?
Encapsulation, abstraction, inheritance, and polymorphism. Python supports encapsulation through naming conventions and properties, abstraction through the abc module and abstract base classes, inheritance including multiple inheritance, and polymorphism through duck typing and method overriding.
What is self in Python classes?
self is the conventional name for the first parameter of instance methods, and it refers to the current instance. Python passes the instance automatically when you call a method, so obj.method() becomes Class.method(obj) internally. The name self is a convention, not a keyword.
What is the difference between __init__ and __new__?
__new__ is the actual constructor that creates and returns a new instance, while __init__ initialises that already-created instance. You rarely override __new__ except for immutable types or singletons. For most classes, only __init__ is needed.
What is the difference between class methods, static methods, and instance methods?
Instance methods take self and can access instance state. Class methods take cls via the @classmethod decorator and operate on the class, often used as alternative constructors. Static methods use @staticmethod, take neither self nor cls, and are just plain functions grouped inside a class for organisation.
class Job:
company = "Goodspace"
def instance_m(self): ...
@classmethod
def class_m(cls): return cls.company
@staticmethod
def static_m(): return "utility"
How does Python implement encapsulation and private attributes?
Python has no true private members. A single leading underscore signals "internal, please do not touch." A double leading underscore triggers name mangling, so __value becomes _ClassName__value, which discourages accidental access from subclasses. It is a convention-based system, not enforced privacy.
What is method resolution order (MRO)?
MRO is the order in which Python searches base classes for a method or attribute during inheritance. Python uses the C3 linearisation algorithm, and you can inspect it with ClassName.__mro__ or ClassName.mro(). It is what makes multiple inheritance predictable and is why super() works correctly in diamond hierarchies.
What does the super() function do?
super() returns a proxy object that lets you call methods of a parent or the next class in the MRO. It is commonly used to call the parent __init__ so that base-class initialisation runs. Using super() instead of naming the parent directly keeps multiple inheritance working correctly.
What is duck typing?
Duck typing means Python cares about what an object can do, not what type it is. If an object implements the required methods, it can be used, regardless of its class. The name comes from "if it walks like a duck and quacks like a duck, it is a duck." This is why Python often skips explicit interfaces.
Functions and Decorators
What is a lambda function?
A lambda is a small anonymous function defined with the lambda keyword. It can take multiple arguments but contains only a single expression, whose value is returned automatically. Lambdas are handy for short callbacks passed to sorted, map, and filter.
add = lambda x, y: x + y
print(add(2, 3)) # 5
What is a decorator and how does it work?
A decorator is a function that takes another function and returns a modified or wrapped version, without changing the original source. It is applied with the @ syntax and is commonly used for logging, timing, authentication, and caching.
def logger(fn):
def wrapper(*args, **kwargs):
print(f"Calling {fn.__name__}")
return fn(*args, **kwargs)
return wrapper
@logger
def greet(name):
return f"Hi {name}"
What is the difference between a generator and a normal function?
A normal function returns once and computes its whole result. A generator uses yield to produce values lazily, one at a time, pausing and resuming its state between calls. Generators are memory efficient because they do not build the entire sequence in memory, which is ideal for large or streaming data.
def counter(n):
for i in range(n):
yield i
What are closures in Python?
A closure is a nested function that remembers and accesses variables from its enclosing scope even after that outer function has finished executing. Closures are the mechanism that makes decorators and function factories work.
What is the difference between map(), filter(), and reduce()?
map() applies a function to every item and returns the transformed items. filter() keeps only the items for which a function returns true. reduce(), from functools, folds a sequence into a single value by applying a function cumulatively. Comprehensions often replace map and filter in idiomatic Python.
What are Python namespaces and the LEGB rule?
A namespace maps names to objects. Python resolves names using the LEGB rule: Local, Enclosing, Global, then Built-in scope, searched in that order. Understanding LEGB explains shadowing bugs and when to use the global and nonlocal keywords.
What do the global and nonlocal keywords do?
global lets a function rebind a name in the module-level scope. nonlocal lets a nested function rebind a name in the nearest enclosing function scope rather than creating a new local. Without them, assignment inside a function always creates a new local variable.
Exceptions and Error Handling
How does exception handling work in Python?
You wrap risky code in a try block, handle specific errors in except blocks, run cleanup in finally, and optionally use else for code that runs only when no exception occurred. Catching specific exception classes is preferred over a bare except.
try:
value = 10 / x
except ZeroDivisionError:
value = 0
else:
print("no error")
finally:
print("always runs")
What is the difference between an error and an exception?
Syntax errors are detected before execution and stop the program from running at all. Exceptions occur during execution and can be caught and handled, allowing the program to recover or fail gracefully. Most interview scenarios deal with exceptions.
How do you create a custom exception?
Subclass the built-in Exception class, or a more specific exception, and raise it with raise. Custom exceptions make error handling in larger applications clearer and more targeted.
class PaymentError(Exception):
pass
raise PaymentError("Card declined")
What does the with statement and a context manager do?
The with statement wraps a block so that setup and teardown happen automatically, even if an exception occurs. It relies on context managers that implement __enter__ and __exit__. The classic example is file handling, where the file is closed automatically when the block ends.
Modules, Libraries, and Environments
What is the difference between a module and a package?
A module is a single .py file containing Python code. A package is a directory of modules, historically identified by an __init__.py file, that groups related modules under a namespace. Packages let you organise large codebases and avoid name collisions.
What is pip and what is a virtual environment?
pip is Python's package installer that fetches libraries from the Python Package Index. A virtual environment, created with venv or tools like virtualenv, isolates a project's dependencies so different projects can use different library versions without conflict. Interviewers expect you to mention requirements.txt for reproducibility.
What is the difference between import module and from module import name?
import module brings in the whole module and you access members with the module prefix. from module import name brings a specific name directly into your namespace. The first keeps names namespaced and readable, while the second is more concise but risks name clashes.
What does the if __name__ == "__main__" idiom do?
When a file is run directly, its __name__ is set to "__main__", but when it is imported, __name__ is the module's name. This guard lets code run only when the file is executed directly, not when it is imported, which is useful for tests and scripts.
Memory Management and Performance
How does Python manage memory?
Python uses a private heap managed by the interpreter, reference counting as the primary mechanism, and a cyclic garbage collector to clean up reference cycles. The gc module exposes controls, and a memory allocator called pymalloc handles small objects efficiently. You do not allocate or free memory manually.
What is the Global Interpreter Lock (GIL)?
The GIL is a mutex in CPython that allows only one thread to execute Python bytecode at a time. It simplifies memory management but prevents CPU-bound multithreading from using multiple cores. For CPU-bound work use multiprocessing, and for I/O-bound work threads or asyncio still help because the GIL is released during I/O.
When would you use multithreading versus multiprocessing?
Use multithreading for I/O-bound tasks such as network calls and file reads, where threads wait and the GIL is released. Use multiprocessing for CPU-bound tasks such as heavy computation, since separate processes each have their own interpreter and GIL and can run on multiple cores.
How can you make Python code faster?
Choose efficient data structures, use built-in functions and comprehensions, avoid unnecessary work inside loops, cache repeated results with functools.lru_cache, use generators for large data, move hot paths to libraries like NumPy, and profile with cProfile before optimising. The rule is to measure first, then optimise the real bottleneck.
What is the difference between range and xrange?
In Python 3, range returns a lazy, memory-efficient sequence object, which is what xrange did in Python 2. Python 3 removed xrange entirely. Mentioning this shows awareness of the Python 2 to 3 migration, which still comes up in legacy codebases.
Coding and Output Questions
The fastest way to get comfortable answering these out loud is a timed AI Mock Interview where you explain your reasoning under light pressure, exactly like a real screening round. Reading answers is easy, speaking them clearly is the skill that gets scored.
Reverse a string without a loop
s = "python"
print(s[::-1]) # nohtyp
Slicing with a step of -1 is the most Pythonic way and is what interviewers expect first.
Check whether a string is a palindrome
def is_palindrome(s):
s = s.lower()
return s == s[::-1]
Mention that you might strip spaces and punctuation for real-world text.
Find duplicates in a list
def duplicates(items):
seen, dupes = set(), set()
for x in items:
if x in seen:
dupes.add(x)
seen.add(x)
return list(dupes)
Using a set keeps this at O(n) time instead of a nested loop.
What is the output of this mutable default argument?
def add(item, target=[]):
target.append(item)
return target
print(add(1)) # [1]
print(add(2)) # [1, 2]
The default list is created once when the function is defined, so it is shared across calls. This is a classic trap. The fix is to default to None and create a fresh list inside the function.
Count word frequency in a sentence
from collections import Counter
text = "job job interview goodspace job"
print(Counter(text.split()))
# Counter({'job': 3, 'interview': 1, 'goodspace': 1})
Swap two variables without a temporary variable
a, b = b, a
Python's tuple packing and unpacking makes this a one-liner, unlike many other languages.
What does this list comprehension with a condition produce?
evens = [n for n in range(10) if n % 2 == 0]
# [0, 2, 4, 6, 8]
Comprehensions read left to right: the expression, then the loop, then the filter.
Python for Data and Backend Roles (Experienced)
What is the difference between NumPy arrays and Python lists?
NumPy arrays store elements of a single type in contiguous memory, which makes vectorised numeric operations far faster and more memory efficient than lists. Lists are flexible and can hold mixed types but are slower for math-heavy work. For data science, NumPy is the foundation that Pandas builds on.
What is a Pandas DataFrame?
A DataFrame is a two-dimensional, labelled, tabular data structure in Pandas, similar to a spreadsheet or SQL table, with rows and named columns. It supports filtering, grouping, joining, and aggregation, and is the primary tool for data cleaning and analysis in Python.
What is the difference between loc and iloc in Pandas?
loc selects data by label, meaning row and column names, while iloc selects by integer position. Mixing them up is a common bug, so interviewers like to test this distinction.
How do WSGI and ASGI differ?
WSGI is the traditional synchronous interface between Python web servers and applications, used by frameworks like Flask and Django's classic stack. ASGI is the asynchronous successor that supports async views, WebSockets, and long-lived connections, used by frameworks like FastAPI. ASGI matters for high-concurrency backend roles.
What is the difference between Flask and Django?
Django is a batteries-included framework with a built-in ORM, admin panel, authentication, and strong conventions, suited to large applications. Flask is a lightweight micro-framework that gives you freedom to pick your own components, suited to smaller services and APIs. FastAPI is a common third option for async APIs with type-based validation.
What is an ORM and why use one?
An ORM, or Object Relational Mapper, lets you work with database rows as Python objects instead of writing raw SQL. It improves productivity, reduces boilerplate, and helps prevent SQL injection. The trade-off is a performance and control cost, so experienced engineers know when to drop to raw queries.
How does asyncio work at a high level?
asyncio runs an event loop that schedules coroutines defined with async def. When a coroutine hits an await on an I/O operation, it yields control so the loop can run other tasks, achieving concurrency on a single thread. It shines for high-volume I/O-bound workloads such as API gateways and web scraping.
How to prepare for a Python interview
Start with the fundamentals in this guide and make sure you can explain each concept in your own words, since interviewers probe understanding with follow-up questions. Write real code daily on a platform like LeetCode, HackerRank, or GeeksforGeeks, because Indian placement and screening rounds almost always include live coding. Build one or two small projects, such as a REST API or a data analysis notebook, so you have concrete work to discuss.
For freshers targeting service companies, focus on syntax, OOP, and output-based questions, since those rounds emphasise breadth. For product companies and startups, go deeper on data structures, complexity analysis, and system design fundamentals. Practising with a timed AI Mock Interview helps you rehearse speaking your answers clearly, manage nerves, and get feedback on pacing before the real thing. The engineers who perform best are usually the ones who have already said their answers out loud several times.
Finally, revise the day before rather than cramming new topics, sleep well, and treat the interview as a conversation. Ask clarifying questions, think aloud, and if you do not know something, explain how you would find out. That honesty and problem-solving mindset often matters more than a single perfect answer.
Frequently Asked Questions
Are Python interview questions the same for freshers and experienced candidates?
The core concepts overlap, but the depth differs. Freshers face more syntax, data type, and OOP questions, while experienced candidates get memory management, concurrency, design, and framework questions along with system design.
How many Python questions should I prepare for a placement drive?
Aim to master roughly 40 to 60 conceptual questions plus a solid set of coding problems on strings, lists, dictionaries, and basic algorithms. Quality of understanding matters more than the raw count.
Is Python enough to get a software job in India?
Python alone opens doors in data science, backend, automation, and QA roles, but pairing it with SQL, one framework, and strong problem-solving skills makes you far more competitive across both service and product companies.
What is the most common tricky Python question?
The mutable default argument trap and the difference between is and == are among the most common, because they reveal whether you truly understand how Python objects and references behave.
Should I learn Python 2 or Python 3?
Learn Python 3, since Python 2 reached end of life in 2020. You should still recognise a few Python 2 differences, such as print as a statement and xrange, because legacy code appears in some interviews.
How do I stop freezing during live coding rounds?
Practice under time pressure and speak while you code. Rehearsing with mock interviews trains you to narrate your thought process, which keeps you calm and shows the interviewer how you reason even when the final answer is not perfect.






