The top 40 Python interview questions asked at TCS, Wipro, Infosys, Cognizant, Accenture, and HCL in 2026 fall into seven clusters: data types and mutability (28%), lists/tuples/dicts/sets (22%), OOP concepts (18%), string manipulation (12%), functions and lambdas (10%), file handling and exceptions (6%), and generators/decorators/comprehensions (4%). Most fresher Python interviews include 10–15 MCQs in the screening test (TCS NQT, Wipro NLTH, Infosys InfyTQ), 2–3 live coding questions (FizzBuzz, factorial, palindrome, two-sum), and 1–2 scenario questions (mutable default argument, list vs tuple, GIL impact). This guide gives you all 40 questions with concise answers and 12 working code examples, plus the topic-weightage table that mirrors what TCS NQT and Infosys InfyTQ actually test.
Table of Contents
- Python Topic Weightage in 2026 Fresher Interviews
- Company Round Formats (TCS / Wipro / Infosys)
- Python Basics (Q1–Q8)
- Lists, Tuples, Dicts, Sets (Q9–Q16)
- String Manipulation (Q17–Q20)
- Functions, *args, **kwargs, Lambda (Q21–Q26)
- Object-Oriented Python (Q27–Q33)
- Generators, Decorators, Comprehensions (Q34–Q37)
- File Handling & Exceptions (Q38–Q40)
- 4-Week Python Interview Prep Plan
Python Topic Weightage in 2026 Fresher Interviews
The frequency distribution below is compiled from candidate reports and public preparation resources across recent TCS NQT, Wipro NLTH, and Infosys InfyTQ drives (2023–2025). These are estimated ranges, not measured figures — treat them as a prep-weighting guide rather than exact data.
| Topic Cluster | Frequency in MCQ Round | Frequency in Coding Round |
|---|---|---|
| Data types, mutability, type casting | 28% | 8% |
| Lists, tuples, dicts, sets | 22% | 35% |
| OOPs (inheritance, polymorphism, dunder methods) | 18% | 20% |
| String manipulation | 12% | 18% |
| Functions, *args/**kwargs, lambda | 10% | 10% |
| File handling, exceptions | 6% | 5% |
| Generators, decorators, comprehensions | 4% | 4% |
Key trend: OOPs weight in MCQ rounds grew from ~12% in 2023 to ~18% in 2025. Expect it to stay elevated in 2026 as companies filter for production-readiness, not just scripting ability.
Company Round Formats: TCS NQT, Wipro NLTH, Infosys InfyTQ
| Company Round | Format | Python Coverage |
|---|---|---|
| TCS NQT (2026) | Online MCQ + 1–2 coding questions on HackerRank | Core syntax, OOPs, basic data structures, output prediction |
| Wipro NLTH (2026) | Online MCQ + 1 coding + 1 essay (sometimes) | Core Python, OOPs, error-spotting in code |
| Infosys InfyTQ (2026) | Online MCQ + 1–2 coding (HackerRank-style) | Python fundamentals + 1 class-design question |
| Infosys HackWithInfy (2026) | DSA round + grand finale | Python allowed; harder DSA problems (medium LeetCode level) |
| Cognizant GenC / GenC Next (2026) | Online MCQ + coding | Python + SQL basics; OOPs definition questions |
| Accenture (2026) | Online MCQ + 1–2 coding | Python basics, list/string ops, output tracing |
- Q1. Why is Python so popular — what would you highlight in an interview?
Answer: Readable syntax close to English (fast to learn and maintain), a huge standard library plus the pip ecosystem, and one language serving four job markets at once: web backends (Django/Flask), data analysis (Pandas/NumPy), automation and scripting, and AI/ML (PyTorch/TensorFlow). Dynamic typing and an interpreter make the edit-run loop very fast. Most fresher interviewers want a one-paragraph answer that ties Python's popularity to a concrete job-market outcome (not just "it's easy").
- Q2. Is Python interpreted or compiled?
Answer: Both, technically. Source is first compiled to bytecode (a .pyc file), which the Python Virtual Machine then interprets line by line. In interviews, say "interpreted language with a bytecode compilation step" — that phrasing shows you know what actually happens, not just the textbook label. CPython is the default implementation that does this; PyPy is a faster JIT-compiled alternative.
- Q3. What is the difference between a list and a tuple?
Answer: A list is mutable (you can add, remove, or change elements after creation) and uses square brackets [ ]. A tuple is immutable (cannot be changed after creation) and uses parentheses ( ). Lists are slower but more flexible; tuples are faster and hashable so they can be dict keys or set members. Use lists when the collection will change; use tuples when it represents a fixed record (a coordinate, a database row).
- Q4. Which data types are mutable vs immutable in Python?
Answer: Mutable: list, dict, set, bytearray. Immutable: int, float, bool, str, tuple, frozenset, bytes. The interview trap question: "Is a tuple containing a list mutable?" — the tuple itself cannot be reassigned, but the list inside it can be mutated. So technically yes, the contents can change.
- Q5. What is the difference between
is and == in Python?
Answer: == compares values (calls __eq__). is compares identity (whether two names point to the same object in memory). For small integers and short strings, Python caches objects so is may return True even when you expect == to be the safer check. The interview answer: use == for value comparison, use is only for singleton checks like x is None.
- Q6. What is dynamic typing in Python?
Answer: Variable names are bound to objects at runtime, not declared with a type. The same name can refer to different types in different lines: x = 5, then x = "hello", then x = [1, 2] all work. Contrast with statically typed languages (Java, C++) where types are declared at compile time. This makes Python fast to write but means type bugs surface at runtime, not at edit time — which is why type hints (def add(a: int, b: int) -> int) were added in PEP 484.
- Q7. What is the difference between
bytes and str in Python?
Answer: str holds Unicode text (a sequence of Unicode code points). bytes holds raw 8-bit values (a sequence of integers 0–255). You cannot mix them in operations; you must explicitly encode str → bytes ("hello".encode("utf-8")) or decode bytes → str (b"hello".decode("utf-8")). Files opened in text mode return str; files opened in binary mode ("rb") return bytes.
- Q8. How does Python handle integer overflow?
Answer: Python integers have arbitrary precision — they grow as needed until memory runs out. No silent overflow like in C or Java's int. Floats still overflow to inf and underflow to 0.0. The interview answer: 2 ** 1000 returns a 302-digit integer in Python; the same expression in Java without BigInteger would overflow.
Lists, Tuples, Dicts, Sets (Q9–Q16)
- Q9. How do you sort a list of dicts by a key?
Answer: data = [
{"name": "Asha", "salary": 75000},
{"name": "Ravi", "salary": 92000},
{"name": "Meera", "salary": 68000},
]
sorted_data = sorted(data, key=lambda d: d["salary"], reverse=True)
# [{'name': 'Ravi', 'salary': 92000},
# {'name': 'Asha', 'salary': 75000},
# {'name': 'Meera', 'salary': 68000}]For multiple keys, return a tuple: key=lambda d: (d["dept"], -d["salary"]) — or use operator.itemgetter("dept", "salary"). Python's sort is stable, so equal elements keep their original order.
Answer: Readable syntax close to English (fast to learn and maintain), a huge standard library plus the pip ecosystem, and one language serving four job markets at once: web backends (Django/Flask), data analysis (Pandas/NumPy), automation and scripting, and AI/ML (PyTorch/TensorFlow). Dynamic typing and an interpreter make the edit-run loop very fast. Most fresher interviewers want a one-paragraph answer that ties Python's popularity to a concrete job-market outcome (not just "it's easy").
Answer: Both, technically. Source is first compiled to bytecode (a
.pyc file), which the Python Virtual Machine then interprets line by line. In interviews, say "interpreted language with a bytecode compilation step" — that phrasing shows you know what actually happens, not just the textbook label. CPython is the default implementation that does this; PyPy is a faster JIT-compiled alternative.Answer: A list is mutable (you can add, remove, or change elements after creation) and uses square brackets
[ ]. A tuple is immutable (cannot be changed after creation) and uses parentheses ( ). Lists are slower but more flexible; tuples are faster and hashable so they can be dict keys or set members. Use lists when the collection will change; use tuples when it represents a fixed record (a coordinate, a database row).Answer: Mutable:
list, dict, set, bytearray. Immutable: int, float, bool, str, tuple, frozenset, bytes. The interview trap question: "Is a tuple containing a list mutable?" — the tuple itself cannot be reassigned, but the list inside it can be mutated. So technically yes, the contents can change.is and == in Python?Answer:
== compares values (calls __eq__). is compares identity (whether two names point to the same object in memory). For small integers and short strings, Python caches objects so is may return True even when you expect == to be the safer check. The interview answer: use == for value comparison, use is only for singleton checks like x is None.Answer: Variable names are bound to objects at runtime, not declared with a type. The same name can refer to different types in different lines:
x = 5, then x = "hello", then x = [1, 2] all work. Contrast with statically typed languages (Java, C++) where types are declared at compile time. This makes Python fast to write but means type bugs surface at runtime, not at edit time — which is why type hints (def add(a: int, b: int) -> int) were added in PEP 484.bytes and str in Python?Answer:
str holds Unicode text (a sequence of Unicode code points). bytes holds raw 8-bit values (a sequence of integers 0–255). You cannot mix them in operations; you must explicitly encode str → bytes ("hello".encode("utf-8")) or decode bytes → str (b"hello".decode("utf-8")). Files opened in text mode return str; files opened in binary mode ("rb") return bytes.Answer: Python integers have arbitrary precision — they grow as needed until memory runs out. No silent overflow like in C or Java's
int. Floats still overflow to inf and underflow to 0.0. The interview answer: 2 ** 1000 returns a 302-digit integer in Python; the same expression in Java without BigInteger would overflow.Answer:
data = [
{"name": "Asha", "salary": 75000},
{"name": "Ravi", "salary": 92000},
{"name": "Meera", "salary": 68000},
]
sorted_data = sorted(data, key=lambda d: d["salary"], reverse=True)
# [{'name': 'Ravi', 'salary': 92000},
# {'name': 'Asha', 'salary': 75000},
# {'name': 'Meera', 'salary': 68000}]For multiple keys, return a tuple: key=lambda d: (d["dept"], -d["salary"]) — or use operator.itemgetter("dept", "salary"). Python's sort is stable, so equal elements keep their original order.
Answer:
items = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
unique = list(dict.fromkeys(items))
# [3, 1, 4, 5, 9, 2, 6]set(items) removes duplicates but destroys order. The dict.fromkeys() idiom preserves order because dict keys are insertion-ordered since Python 3.7. Time complexity: O(n).
Answer: Three cases: (1) membership testing —
if x in seen_set is O(1), whereas if x in seen_list is O(n); (2) de-duplication — set(list_with_dups); (3) set algebra — union, intersection, difference turn "items in A but not in B" into one readable expression: set(a) - set(b). Sets require hashable elements, so lists cannot be set members but tuples can.Answer:
a = {"x": 1, "y": 2}
b = {"y": 3, "z": 4}
# Python 3.9+ clean syntax
merged = a | b # {'x': 1, 'y': 3, 'z': 4} (b wins on conflicts)
# Older syntax (still works)
merged = {**a, **b} # same result
# In-place update
a |= b # a is now {'x': 1, 'y': 3, 'z': 4}On key conflicts, the rightmost dict wins. For deep merging nested dicts you need collections.ChainMap or a recursive helper.
Answer: Tuples are smaller and faster. For a tuple of three integers, Python stores a fixed-size struct; for a list of the same three integers, Python stores pointers to three separate objects plus a dynamic array header. In CPython,
sys.getsizeof((1,2,3)) returns 64 bytes vs sys.getsizeof([1,2,3]) returning 88 bytes — and the gap widens as elements grow.Answer:
fruits = ["apple", "banana", "cherry"]
# Pythonic: enumerate
for i, fruit in enumerate(fruits):
print(i, fruit)
# 0 apple
# 1 banana
# 2 cherry
# Avoid: range + len
for i in range(len(fruits)):
print(i, fruits[i]) # works, but not idiomaticUse enumerate() — cleaner and faster than range(len(...)).
Answer:
lst[start:stop:step] returns a new list from start (inclusive) to stop (exclusive), stepping by step. Defaults: start=0, stop=len(lst), step=1. Negative indices count from the end: lst[-3:] gives the last three elements. Slicing never raises IndexError for out-of-range — it silently clamps. lst[::-1] reverses the list.Answer: Three ways, with different semantics:
String Manipulation (Q17–Q20)
- Q17. How do you reverse a string in Python?
Answer:s = "python" reversed_s = s[::-1] # 'nohtyp' # Or with reversed() + join: reversed_s = ''.join(reversed(s)) # 'nohtyp'Slicing is the idiomatic answer. Time complexity O(n). For palindrome checks:
if s == s[::-1]: print("palindrome").
str.find() and str.index()?Answer: Both return the lowest index where the substring is found.
find() returns -1 when not found (safe, no exception). index() raises ValueError when not found. Use find() for "does it contain?" checks; use index() when absence is a bug you want to surface immediately.Answer:
csv = "asha,ravi,meera"
names = csv.split(",") # ['asha', 'ravi', 'meera']
joined = ", ".join(names) # 'asha, ravi, meera'
# Common interview: reverse words in a sentence
sentence = "the quick brown fox"
reversed_words = " ".join(sentence.split()[::-1]) # 'fox brown quick the'Answer: Formatted string literals (PEP 498, Python 3.6+). Inline expressions inside
{ }:Functions, *args, **kwargs, Lambda (Q21–Q26)
- Q21. What is the difference between
*argsand**kwargs?
Answer:def make_profile(name, *hobbies, **details): print(f"Name: {name}") print(f"Hobbies: {hobbies}") print(f"Details: {details}") make_profile("Asha", "reading", "hiking", age=29, city="Bangalore", role="Engineer") # Name: Asha # Hobbies: ('reading', 'hiking') # Details: {'age': 29, 'city': 'Bangalore', 'role': 'Engineer'}*argscollects extra positional arguments into a tuple.**kwargscollects extra keyword arguments into a dict. Order in the signature: positional →*args→ keyword-only →**kwargs. - Q22. What are
defaultarguments and what is the mutable-default trap?
Answer:# WRONG — default list is shared across calls def add_item(item, bucket=[]): bucket.append(item) return bucket print(add_item("a")) # ['a'] print(add_item("b")) # ['a', 'b'] ← surprise! # CORRECT — use None as sentinel def add_item(item, bucket=None): if bucket is None: bucket = [] bucket.append(item) return bucketThe default is evaluated once at function-definition time, not on each call. This is one of the most common interview traps in Python and a frequent source of production bugs.
- Q23. What is a lambda function?
Answer: An anonymous single-expression function:lambda args: expression. Useful for short throwaway functions passed tosorted(),map(),filter(). Avoid for anything that needs a statement (assignment, try/except, multi-line logic) — usedefinstead. Lambdas are syntactically restricted to a single expression; PEP 8 assigns them a name only when the assignment is clearer than the inline form. - Q24. What is a closure in Python?
Answer:def make_multiplier(factor): def multiply(x): return x * factor return multiply double = make_multiplier(2) triple = make_multiplier(3) print(double(5), triple(5)) # 10 15 # `multiply` captures `factor` from the enclosing scope. # Common use: factory functions, decorators. - Q25. What is the difference between
map(),filter(), and a comprehension?
Answer:nums = [1, 2, 3, 4, 5] # map: apply a function to each element squares = list(map(lambda x: x**2, nums)) # [1, 4, 9, 16, 25] # filter: keep elements where function is True evens = list(filter(lambda x: x % 2 == 0, nums)) # [2, 4] # Comprehension (preferred — more readable, often faster) squares = [x**2 for x in nums] evens = [x for x in nums if x % 2 == 0]Comprehensions are generally preferred over
map/filterfor readability. Usemaponly when you already have a named function and want lazy evaluation (don't wrap inlist()). - Q26. What is a decorator?
Answer:import functools import time def timer(func): @functools.wraps(func) def wrapper(*args, **kwargs): start = time.perf_counter() result = func(*args, **kwargs) elapsed = time.perf_counter() - start print(f"{func.__name__} took {elapsed:.4f}s") return result return wrapper @timer def slow_function(): time.sleep(0.1) slow_function() # slow_function took 0.1003sA decorator is a function that takes another function and returns a wrapped version. Use
@functools.wraps(func)to preserve the original function's metadata (__name__,__doc__). Common uses: timing, logging, authentication, caching (@functools.lru_cache).
Object-Oriented Python (Q27–Q33)
- Q27. What is the difference between a class and an object?
Answer: A class is a blueprint (defines attributes and methods). An object is an instance of that blueprint (a concrete thing in memory with its own state).class Car:defines the blueprint;my_car = Car()creates an instance. Each object has its own copy of instance attributes but shares class attributes with other instances. - Q28. What is the difference between
__init__and__new__?
Answer:__new__creates and returns the instance (called first).__init__initializes the already-created instance (called second, after__new__). For 99% of classes you override__init__; override__new__only when you need to control instance creation itself (immutable subclasses likeint/str, the Singleton pattern, or metaclasses). - Q29. What is Method Resolution Order (MRO) in Python?
Answer:class A: pass class B(A): pass class C(A): pass class D(B, C): pass print(D.__mro__) # (, , , , ) # MRO uses C3 linearization — child classes come before parents, # and order respects the inheritance list.Use
super()in cooperative multiple inheritance to call the next class in the MRO. A diamond inheritance question (like the one above) appears in roughly 1 in 5 Zoho and Freshworks fresher interviews. - Q30. What is the difference between classmethod, staticmethod, and instance methods?
Answer:class Employee: raise_amount = 1.04 # class attribute def __init__(self, name, salary): self.name = name # instance attribute self.salary = salary def apply_raise(self): # instance method — gets self self.salary = int(self.salary * self.raise_amount) @classmethod def set_raise(cls, amount): # class method — gets cls cls.raise_amount = amount @staticmethod def is_workday(day): # static method — no implicit first arg return day.weekday() < 5Instance methods receive
self(the instance). Class methods receivecls(the class) and can modify class state. Static methods receive nothing implicit — they're regular functions namespaced inside the class for organizational clarity. - Q31. What are dunder (magic) methods?
Answer: Methods with double underscores at both ends that let you define how built-in operations behave on your objects:__str__(str() and print),__repr__(the unambiguous representation for debugging),__len__(len()),__eq__(==),__lt__(<),__add__(+),__getitem__(obj[key]),__iter__(for loops),__enter__/__exit__(with statements). Implementing them is how you make your objects behave like Python built-ins. - Q32. What is encapsulation in Python?
Answer: Bundling data and the methods that operate on that data into a single unit (a class). Python uses conventions rather than enforced access modifiers: a single underscore prefix (_internal_var) signals "private by convention" and a double underscore prefix (__mangled) triggers name mangling (the attribute becomes_ClassName__mangled). But Python's philosophy is "we are all consenting adults" — nothing is truly private. - Q33. What is the difference between inheritance and composition?
Answer: Inheritance (class Child(Parent)) models an "is-a" relationship (aSavingsAccountis aAccount). Composition (self.engine = Engine()) models a "has-a" relationship (aCarhas anEngine). Prefer composition over inheritance when there's no clean "is-a" relationship — it keeps class hierarchies shallow and avoids the fragile-base-class problem. The interview answer: "favor composition; use inheritance only when there's a true type-substitution need."
Generators, Decorators, Comprehensions (Q34–Q37)
- Q34. What is a generator and how does it differ from a list?
Answer:# List comprehension — builds the entire list in memory squares_list = [x*x for x in range(1_000_000)] # ~8 MB # Generator expression — produces one value at a time on demand squares_gen = (x*x for x in range(1_000_000)) # ~120 bytes # Total memory: list holds 1M ints; generator holds only the loop state. # Use generators for large or infinite sequences (streaming, file lines, sensors). - Q35. What is the
yieldkeyword?
Answer: Turns a function into a generator. Eachyieldpauses the function and returns a value; the next call tonext()resumes from where it stopped, with all local state intact. This is what makes generators memory-efficient for streaming large data — a 10GB log file processed line-by-line with a generator uses constant memory, while a list comprehension would crash on a typical machine. - Q36. What is a list comprehension vs a generator expression?
Answer:# List — eager [x*x for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # Generator — lazy (x*x for x in range(10)) # generator object at 0x7f...> # Use generator when: # - the sequence is large or potentially infinite # - you only need each value once (e.g., in sum() or any()) # Use list when: # - you need random access (lst[i]), len(), or to iterate multiple times - Q37. What is a decorator and how do you chain them?
Answer:@functools.lru_cache(maxsize=128) @timer def fib(n): return n if n < 2 else fib(n-1) + fib(n-2) # Decorators apply bottom-up: # fib = timer(fib) # inner wrapper # fib = lru_cache(fib) # outer wrapper # So lru_cache calls the timer-wrapped version, # and the timer measures each cached or uncached call.
File Handling & Exceptions (Q38–Q40)
- Q38. What is the difference between
try/except/finallyand thewithstatement?
Answer:# Verbose: try/finally ensures cleanup f = open("data.txt") try: contents = f.read() finally: f.close() # Idiomatic: with-statement (context manager) with open("data.txt") as f: contents = f.read() # f.close() runs automatically even if an exception is raised. # Write your own context manager: import contextlib @contextlib.contextmanager def timer_block(label): start = time.perf_counter() yield print(f"{label}: {time.perf_counter() - start:.4f}s") with timer_block("compute"): sum(range(10_000_000)) - Q39. How do you read a huge file without running out of memory?
Answer:# Iterate line by line (file objects are lazy iterators) with open("huge.log") as f: for line in f: process(line) # For fixed-size chunks (binary or text): with open("huge.bin", "rb") as f: while chunk := f.read(8192): process(chunk) # NEVER read() the whole file if it could be larger than RAM. - Q40. What is the difference between
ValueError,TypeError, andKeyError?
Answer:Exception When it fires Example ValueErrorRight type, wrong value int("abc")— string is not a valid integer literalTypeErrorWrong type entirely "a" + 1— can't add str and intKeyErrorMissing dict key {"a": 1}["b"]— key "b" not presentIndexErrorList index out of range [1, 2][5]AttributeErrorObject has no such attribute None.upper()NameErrorName not defined <print(undefined_var)
ZeroDivisionError1 / 04-Week Python Interview Preparation Plan
| Week | Focus | Daily Target |
|---|---|---|
| Week 1 | Core Python: types, scoping, mutability, comprehensions | 15 MCQs + 1 coding problem (HackerRank Easy) |
| Week 2 | OOPs: classes, inheritance, dunder methods, MRO | 10 MCQs + 1 class-design exercise |
| Week 3 | Data structures: list ops, dict tricks, stack/queue using deque | 2 LeetCode Easy/Medium problems per day |
| Week 4 | Mock tests + company-specific past questions (TCS NQT, InfyTQ) | 1 full mock test (timed) per day |
Resources and Next Steps
The authoritative sources listed above (Python official docs, Real Python, HackerRank, LeetCode, PEP 8) are the canonical references for Python fundamentals and interview preparation. For the full 25-question curated Q&A collection at all difficulty levels (Level 1 foundational, Level 2 intermediate, Level 3 advanced), see the TutorsBot Python Interview Questions hub. For related interview prep, see our SQL Interview Questions, Java Interview Questions, and DBMS Interview Questions guides — all in the same 40-question fresher + experienced format.






