Python Interview Questions for Freshers India 2026: 60 Q&A Across Beginner, Intermediate, and Advanced
Python has been the most popular programming language globally for several consecutive years, and in India's IT hiring market, Python skills are a top requirement across software development, data engineering, data science, automation, and backend development roles. According to the TIOBE Programming Community Index, Python consistently ranks first or second in language popularity, and in India specifically, it is the most commonly tested language in fresher technical interviews after Java.
Whether you are preparing for a Python developer role at a startup, a data engineering position at an IT services company, or a general software engineering role where Python proficiency is tested, this guide provides 60 Python interview questions across beginner, intermediate, and advanced levels, with complete answers. All language-specific behaviour described here is based on Python 3.x official documentation.
Why Python is critical for Indian freshers in 2026
Python's dominance in Indian hiring spans multiple domains:
- Software development: Backend APIs with Flask and Django, scripting and automation
- Data science and analytics: NumPy, Pandas, Matplotlib, Scikit-learn
- AI/ML engineering: TensorFlow, PyTorch (Python is the primary language for both)
- DevOps and cloud: Infrastructure automation, AWS Lambda functions, CI/CD scripting
- Data engineering: ETL pipelines with PySpark, Airflow workflows
Companies from Infosys and Wipro to Swiggy and Zepto test Python in fresher interviews. A strong Python foundation is no longer optional — it is a baseline expectation for modern IT roles.
Part 1: Beginner Python questions (Q1-Q20)
Q1. What are Python's key features? Python is dynamically typed (types are checked at runtime, not compile time), interpreted (executed line by line), object-oriented (supports classes and inheritance), and supports multiple programming paradigms (procedural, functional, OOP). It has extensive standard libraries, a clean indentation-based syntax, and is cross-platform.
Q2. What is the difference between a list and a tuple? A list is mutable (can be changed after creation): [1, 2, 3]. A tuple is immutable (cannot be changed): (1, 2, 3). Tuples are faster to access and can be used as dictionary keys (since they are hashable); lists cannot be used as keys.
Q3. What is a dictionary in Python? A dictionary is an unordered (insertion-ordered since Python 3.7) collection of key-value pairs. Keys must be unique and hashable. Key operations: dict['key'] to access, dict['key'] = value to assign, dict.get('key', default) to safely access with a fallback, and dict.items() to iterate over key-value pairs.
Q4. What is the difference between == and is in Python? == checks value equality: [1, 2] == [1, 2] is True. The keyword "is" checks identity — whether two variables reference the same object in memory. For small integers (minus 5 to 256) and short strings, Python caches objects, so "is" may be True even for seemingly different assignments. Always use == for value comparison.
Q5. What are Python's built-in data types? Numeric: int, float, complex. Text: str. Sequence: list, tuple, range. Mapping: dict. Set types: set, frozenset. Boolean: bool. Binary: bytes, bytearray, memoryview. None type: NoneType.
Q6. What is list slicing in Python? Slicing extracts a portion of a list (or string, tuple) using the syntax list[start:stop:step]. The stop index is exclusive. For example, [1,2,3,4,5][1:4] returns [2,3,4]. Reversing: [1,2,3,4,5][::-1] gives [5,4,3,2,1].
Q7. What is a list comprehension? A concise way to create a list from an iterable: [expression for item in iterable if condition]. Example: [x*x for x in range(10) if x % 2 == 0] produces [0, 4, 16, 36, 64]. List comprehensions are faster than equivalent for-loops because they are optimised at the C level in CPython.
Q8. What is the difference between append() and extend() for lists? append(item) adds a single item to the end: [1,2].append([3,4]) gives [1, 2, [3, 4]]. extend(iterable) adds every element of the iterable: [1,2].extend([3,4]) gives [1, 2, 3, 4].
Q9. How do you reverse a string in Python? Using slicing: s[::-1]. For example, 'hello'[::-1] returns 'olleh'. This is the most idiomatic Python approach and the preferred answer in interviews.
**Q10. What is the *args and kwargs syntax? *args collects extra positional arguments into a tuple inside a function. **kwargs collects extra keyword arguments into a dictionary. Both can be combined: def f(a, *args, **kwargs). This is commonly used to write flexible functions that accept variable numbers of arguments.
Q11. What is the difference between pass, continue, and break? break exits the enclosing loop immediately. continue skips the rest of the current iteration and moves to the next. pass is a no-op statement used as a placeholder where syntactically a statement is required but no action is needed.
Q12. What is a lambda function? An anonymous function defined in a single expression. For example: square = lambda x: x*x. Lambdas are most useful as arguments to higher-order functions like map(), filter(), and sorted(). Example: sorted(people, key=lambda p: p['age']) sorts a list of dicts by the age field.
Q13. What is the difference between range() in Python 2 vs Python 3? In Python 3, range() returns a lazy range object that generates numbers on demand (memory-efficient). In Python 2, range() returned a list in memory, while xrange() returned a lazy iterator. Since xrange() no longer exists in Python 3, this question tests your awareness of Python version differences.
Q14. How do you handle exceptions in Python? Using try/except/else/finally blocks. The try block contains code that might raise an exception. except ExceptionType catches specific errors. else runs only if no exception occurred. finally always runs, used for cleanup (closing files, releasing connections). Catching bare Exception is possible but bad practice — always catch specific exception types.
Q15. What is the with statement used for? Context managers ensure resources are properly cleaned up after use, even if an exception occurs. Opening files with "with open('file.txt', 'r') as f:" automatically closes the file after the block. Context managers implement enter and exit dunder methods.
Q16. What is string formatting in Python? Three main approaches: old % formatting, .format() method, and f-strings (Python 3.6+, preferred). F-strings are fastest, most readable, and support inline expressions. They use the syntax f"Hello {name}" or f"Result: {2 + 2}".
Q17. What is the difference between shallow copy and deep copy? A shallow copy creates a new object but references the same nested objects — modifying nested items in the copy affects the original. A deep copy creates a completely independent copy, recursively copying all nested objects. Use copy.copy() for shallow and copy.deepcopy() for deep copies.
Q18. What are Python's mutable and immutable types? Immutable: int, float, str, tuple, frozenset, bytes. Once created, their values cannot be changed — any operation creates a new object. Mutable: list, dict, set, bytearray. Their values can be changed in place.
Q19. How do you remove duplicates from a list while preserving order? Use dict.fromkeys(): list(dict.fromkeys(original_list)). In Python 3.7+, dicts maintain insertion order, so this preserves the original sequence while removing duplicates. Converting to set() and back removes duplicates but loses order.
Q20. What is None in Python? None is Python's null value — the singleton object of the NoneType class. Functions that do not explicitly return a value return None. Always check for None using "is None" rather than "== None", because "is" correctly checks identity against the singleton.
Part 2: Intermediate Python questions (Q21-Q40)
Q21. What are decorators in Python? A decorator is a function that takes another function as input and returns a modified version, adding behaviour before or after the original function runs without changing its source code. The @decorator_name syntax is shorthand for func = decorator_name(func). Common use cases: logging, timing, authentication, caching, input validation.
Q22. What are generators in Python? A generator is a function that uses yield instead of return, producing a lazy iterator that generates values one at a time. Unlike a function that returns a full list, a generator computes each value on demand, saving memory. Generator expressions like (x*x for x in range(1000)) use far less memory than list equivalents. The key benefit is that you can iterate over large or infinite sequences without storing them all in memory.
Q23. What is the difference between str and repr? repr provides an unambiguous string representation for developers — ideally one that could recreate the object, like Point(x=3, y=4). str provides a human-readable string for display. When you print an object, Python calls str. In the REPL or debugger, repr is called. If only repr is defined, it is used for both purposes.
Q24. What is method resolution order (MRO)? MRO determines the order in which Python searches for methods in a class hierarchy during inheritance. Python uses the C3 linearisation algorithm. View MRO using ClassName.mro. This matters in multiple inheritance — Python resolves which parent's method to call when multiple parents define the same method name.
Q25. What is the difference between a class method, static method, and instance method? An instance method takes self as first argument and can access and modify instance state. A class method decorated with @classmethod takes cls as first argument and can access class-level state. A static method decorated with @staticmethod takes no implicit argument and cannot access instance or class state — it is a utility function scoped to the class.
Q26. What is Python's property decorator? The @property decorator allows a method to be accessed like an attribute, enabling computed properties and validation. Combined with @attribute.setter, you can control how a value is set. This is the Pythonic way to implement getters and setters without changing the public API of a class.
Q27. What are dunder (magic) methods? Methods with double underscores before and after their name, called automatically by Python's built-in operations. add is called by the + operator, len by len(), iter when iterating, contains by the in operator, eq for ==, lt for less-than. Implementing these makes custom classes work naturally with Python's built-in syntax.
Q28. 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, even on multi-core systems. This limits true thread-level parallelism for CPU-bound work. Solutions for CPU parallelism: the multiprocessing module (separate processes bypass the GIL) or using C-extension libraries like NumPy that release the GIL during computation.
Q29. What is the difference between map(), filter(), and reduce()? map(func, iterable) applies a function to each element, returning an iterator. filter(func, iterable) keeps elements where func returns True. reduce(func, iterable) from functools cumulatively applies the function to reduce the iterable to a single value. All three return iterators in Python 3 (not lists) — wrap in list() to materialise.
Q30. What is a context manager and how do you create one? A context manager handles setup and teardown with the with statement. Two approaches: implement enter and exit in a class, or use the @contextmanager decorator from contextlib with a generator function where yield separates setup (before yield) from teardown (after yield).
Q31. What is a named tuple? collections.namedtuple creates tuple subclasses with named fields. For example: Point = namedtuple('Point', ['x', 'y']). Named tuples are immutable, memory-efficient (no dict), and self-documenting — you access fields by name rather than index, making code more readable than plain tuples.
Q32. What is the collections module? The collections module provides specialised data structures beyond the built-ins: Counter (count element frequencies), defaultdict (dict with a default value factory), deque (double-ended queue with O(1) operations at both ends), OrderedDict (maintains insertion order), namedtuple, and ChainMap (merges multiple dicts into a single view).
Q33. How does Python's garbage collection work? Python primarily uses reference counting — each object tracks how many references point to it; when the count reaches zero, memory is freed immediately. A cyclic garbage collector (in the gc module) handles circular references that reference counting cannot resolve. This runs periodically rather than on every deallocation.
Q34. What is the difference between a module and a package in Python? A module is a single Python file (.py) containing functions, classes, and variables. A package is a directory containing multiple modules and an init.py file (which can be empty). Packages allow organising related modules into a namespace hierarchy: import mypackage.mymodule.
Q35. What is pickling in Python? Pickling is the process of serialising a Python object into a byte stream using the pickle module. Unpickling is the reverse — reconstructing the object from bytes. Used for saving model state in ML, caching computed results, and inter-process communication. Warning: never unpickle data from untrusted sources — it can execute arbitrary code.
Q36. What is the difference between is and == for strings? == tests string value equality: 'hello' == 'hello' is always True. "is" tests object identity — Python interns (caches) short strings, so two identical short strings may share the same object in memory. For long strings or runtime-computed strings, "is" may return False even for equal values. Always use == for string comparison.
Q37. What is a frozenset? A frozenset is an immutable version of a set. Like a set, it contains unique elements; unlike a set, it cannot be modified after creation. Frozensets are hashable and can be used as dictionary keys or as elements in another set — regular sets cannot.
Q38. What is the walrus operator (:=)? Introduced in Python 3.8, the walrus operator (named assignment expression) assigns a value within an expression. Example: if (n := len(data)) > 10: print(f"Too long: {n} items"). It avoids computing the same value twice — useful in while loops and comprehensions.
Q39. What is the difference between @staticmethod and a module-level function? Both are functions that do not receive a class or instance reference. The difference is scoping and intent: a static method is namespaced within the class (accessed as MyClass.my_func()), making it clear it belongs to the class conceptually. A module-level function is standalone. Use static methods when the function is logically associated with the class but does not need class or instance access.
Q40. What is functools.lru_cache? A decorator from functools that caches the results of a function call based on its arguments. If the function is called with the same arguments again, it returns the cached result instead of recomputing. Useful for recursive functions (like Fibonacci) and expensive computations. The maxsize parameter limits how many results are cached.
Part 3: Advanced Python questions (Q41-Q60)
Q41. What is a metaclass in Python? A metaclass is a class whose instances are classes. Just as a class defines how instances behave, a metaclass defines how classes behave. The default metaclass is type. Custom metaclasses intercept class creation and can add, modify, or validate class attributes automatically. Used in frameworks like Django's ORM and SQLAlchemy to add database behaviour to model classes.
Q42. What is asyncio and when would you use it? asyncio is Python's framework for writing concurrent code using async/await syntax. It is designed for I/O-bound concurrency (network requests, file operations, database queries) where waiting for external systems is the bottleneck. Use async def to define coroutines and await to pause execution while waiting for I/O. Unlike threads, asyncio uses a single-threaded event loop — avoiding race conditions and GIL issues.
Q43. What are abstract base classes? Abstract base classes (ABCs) from the abc module define interfaces — classes that cannot be instantiated directly and require subclasses to implement specific methods marked with @abstractmethod. ABCs enforce contracts in large codebases: if a subclass does not implement all abstract methods, instantiating it raises TypeError.
Q44. What is slots? By default, Python stores instance attributes in a dict dictionary per object, which has memory overhead. Declaring slots = ['x', 'y'] replaces dict with fixed slots, reducing memory usage by 40-60% for classes with many instances. The tradeoff: you cannot add attributes not listed in slots, and multiple inheritance with slots requires careful design.
Q45. What is the descriptor protocol? Descriptors are objects that define get, set, and/or delete methods, controlling attribute access on other objects. Properties, class methods, and static methods are all implemented using descriptors in Python's data model. Custom descriptors enable reusable attribute validation logic across multiple classes.
Q46. What is the difference between getattr and getattribute? getattribute is called for every attribute access (every time you use dot notation). getattr is called only when the attribute is NOT found through normal means. Override getattr to provide default values for missing attributes; override getattribute only when you need to intercept every attribute access (use with extreme care to avoid infinite recursion).
Q47. What is Python's data model? Python's data model is the system of hooks (dunder methods) that allows objects to integrate with Python's built-in syntax and operations. By implementing add, your object supports +. By implementing iter and next, it supports for loops. By implementing len and getitem, it supports len() and indexing. The data model makes Python's syntax feel consistent regardless of the type you are working with.
Q48. What is a coroutine? A coroutine is a function defined with async def that can suspend its execution at an await expression and resume later. When awaited, a coroutine runs until it hits an await or returns. Coroutines are the building blocks of asyncio-based concurrency. They are more lightweight than threads — you can run thousands of coroutines concurrently in a single thread.
Q49. What is the difference between init and new? new creates the instance (allocates memory) and must return an instance of the class. init initialises the instance after new creates it. new is called first; init is then called with the returned instance. Override new only when subclassing immutable types (like str or int) or implementing singleton patterns.
Q50. What is the itertools module? itertools provides fast, memory-efficient tools for working with iterators. Key functions: itertools.chain() — chains multiple iterables together. itertools.product() — Cartesian product (like nested for loops). itertools.combinations() and itertools.permutations() for combinatorics. itertools.islice() for lazy slicing of iterators. itertools.groupby() for grouping consecutive items by a key.
Pandas and NumPy basics (Q51-Q60)
Q51. What is a Pandas DataFrame? A two-dimensional tabular data structure with labeled rows and columns, similar to a database table or Excel spreadsheet. Key operations: .head() for first N rows, .describe() for statistics, .shape for dimensions, .dtypes for column types, .groupby() for aggregation, .merge() for joining DataFrames, .fillna() for handling missing values.
Q52. What is the difference between .loc and .iloc? .loc is label-based: df.loc[0, 'name'] accesses the row with index label 0 and column 'name'. .iloc is integer position-based: df.iloc[0, 1] accesses the first row and second column by position. When the index is not sequential integers (e.g., after filtering), the distinction matters significantly.
Q53. How do you handle missing values in Pandas? Detect: df.isnull() and df.isnull().sum(). Drop: df.dropna() removes rows with any NaN; df.dropna(axis=1) removes columns. Fill: df.fillna(0), df.fillna(df.mean()), df.fillna(method='ffill') for forward fill. Imputation strategy depends on the data context.
Q54. What is NumPy broadcasting? Broadcasting allows NumPy to perform operations on arrays with different shapes by "stretching" the smaller array along its singleton dimensions to match the larger array. For example, adding a 1D array of shape (3,) to a 2D array of shape (4, 3) broadcasts the 1D array across all 4 rows, avoiding explicit loops.
Q55. What is vectorisation in NumPy? Vectorisation replaces Python loops with NumPy array operations implemented in C, running orders of magnitude faster. Instead of a Python for-loop to add corresponding elements, numpy allows a + b where a and b are arrays — the addition is performed at C speed across all elements simultaneously.
Q56. What is a Pandas Series? A one-dimensional labeled array. A DataFrame is essentially a dictionary of Series objects sharing the same index. Series support vectorised operations, label-based and integer-based indexing, and all standard NumPy operations.
Q57. What is the difference between merge() and concat() in Pandas? concat() stacks DataFrames vertically (row-wise) or horizontally (column-wise) without matching on keys. merge() joins DataFrames based on matching values in one or more columns (like a SQL JOIN). Use concat for stacking, merge for relational combining.
Q58. What is groupby in Pandas? df.groupby('column') splits the DataFrame into groups by unique values in the specified column, then applies an aggregation function to each group. For example: df.groupby('department')['salary'].mean() computes the mean salary per department. The split-apply-combine pattern.
Q59. What is a NumPy ndarray? A NumPy ndarray (n-dimensional array) is a homogeneous, fixed-type, fixed-size multidimensional array. Unlike Python lists, all elements in an ndarray are the same dtype, enabling highly efficient vectorised operations. Key attributes: .shape (dimensions), .dtype (element type), .ndim (number of dimensions), .size (total elements).
Q60. What is the difference between copy() and view() in NumPy? A view is a reference to the original array's data — modifying the view modifies the original. A copy creates a completely independent array — modifying it does not affect the original. Slicing a NumPy array returns a view (not a copy), unlike Python list slicing which always creates a copy. Use .copy() explicitly when you need independence.
5-week Python interview preparation plan
Week 1: Python fundamentals — data types, control flow, functions, built-in methods. Solve 10 easy coding problems in Python daily.
Week 2: OOP in Python — classes, inheritance, polymorphism, dunder methods, properties. Build a small project (linked list implementation, basic bank account class, contact book).
Week 3: Advanced Python — decorators, generators, context managers, asyncio basics, standard library modules (collections, itertools, functools).
Week 4: Data libraries — NumPy array operations, Pandas DataFrame operations, basic data cleaning and manipulation tasks using real datasets.
Week 5: Mock interviews — practise answering Python questions verbally. Use ClavePrep's AI mock interview tool to get feedback on your explanations and communication clarity.
Frequently asked questions
Should I learn Python 2 or Python 3? Python 3 exclusively. Python 2 reached end-of-life in January 2020. All modern projects, libraries, and hiring tests use Python 3.
What is the most important Python topic for IT services company interviews? OOP concepts (classes, inheritance, polymorphism) and data structures (lists, dicts, sets). Most IT services company Python questions are at the beginner-to-intermediate level. Advanced topics like metaclasses are more relevant for product company or senior roles.
Is knowing Python enough to get a data science job as a fresher? Python is necessary but not sufficient. Data science roles also require statistics, SQL, and domain knowledge. Python is sufficient for a junior software developer or automation engineer role.
Should I practise Python on HackerRank or LeetCode? Both. HackerRank is closer to AMCAT and CoCubes coding round formats; LeetCode has broader algorithmic depth. Aim for 50 HackerRank medium problems and 30 LeetCode easy/medium problems before interview season.
What Python version is used in interviews? Python 3.10+ for most modern companies. Some older systems may use 3.8 or 3.9. The differences are minor for interview purposes — focus on core language features rather than version-specific syntax.
Prepare your Python interview answers with ClavePrep
Python interviews test both your code and your ability to explain your thinking. Interviewers want to hear why you chose a particular approach, what the trade-offs are, and how you handle edge cases. Use ClavePrep's AI mock interview to practise verbal Python explanations — not just writing code, but talking through your solutions the way a senior engineer would. Use the STAR Answer Builder for behavioural questions that pair with technical rounds. Start your Python interview preparation at ClavePrep today.
