Top 40 Python Interview Questions and Answers
-
By Devraj
-
13th October 2026
Preparing for a Python interview as a fresher? Interviewers rarely want memorised definitions. They want to see that you understand how Python works, and that you can explain it simply and write small pieces of code. This guide by Skill Hives covers the 40 most common Python interview questions in five parts, with short answers and code you can run yourself. You will also find ten extra questions, four coding tasks, a look at the Indian interview process, and a 7-day revision plan.
Want to turn Python basics into job-ready skills?
Skill Hives offers practical Python training with live projects and mentor guidance.
Part 1: Python Basics (Q1–Q8)
Q1. What is Python and why is it popular?
Python is a high-level, interpreted, general-purpose language. Its syntax is close to English, so it is easy to read and learn. It is used in web development, data science, automation and AI, and it has a huge library ecosystem.
Q2. Is Python compiled or interpreted?
Both. Python first compiles your code into bytecode (the .pyc files in __pycache__), then the Python Virtual Machine runs that bytecode line by line. Most people call it an interpreted language.
Q3. What does “dynamically typed” mean?
You do not declare a variable’s type. Python decides the type from the value at run time, and the same name can hold a different type later.
x = 10 # int
x = "ten" # now a str, no error
Q4. Why is indentation important in Python?
Python uses indentation (spaces) to mark a block of code, where other languages use curly braces. Wrong indentation gives an IndentationError. Use 4 spaces, as PEP 8 recommends.
Q5. What are mutable and immutable types?
Mutable objects can change after creation: list, dict, set. Immutable objects cannot: int, float, str, tuple, frozenset. This is one of the most asked questions, so learn it well.
Q6. What is the difference between a list and a tuple?
A list is mutable and written with []. A tuple is immutable and written with (). Tuples are slightly faster and can be dictionary keys, because they are hashable.
t = (1, 2)
t[0] = 9 # TypeError: 'tuple' object does not support item assignment
Q7. What is the difference between /, //, % and **?
print(7 / 2) # 3.5 true division
print(7 // 2) # 3 floor division
print(-7 // 2) # -4 floor goes down, not toward zero
print(7 % 2) # 1 remainder
print(2 ** 3) # 8 power
Interviewer may ask: what is -7 // 2? The answer is -4, because floor division rounds toward negative infinity.
Q8. What is the difference between == and is?
== checks whether two values are equal. is checks whether two names point to the same object in memory.
a = [1, 2]
b = [1, 2]
c = a
print(a == b) # True
print(a is b) # False
print(a is c) # True
Part 2: Data Types and Collections (Q9–Q18)
Q9. What is a dictionary?
A dictionary stores data as key-value pairs. Keys must be unique and hashable (str, int, tuple). Since Python 3.7 it remembers insertion order.
student = {"name": "Asha", "age": 20}
print(student["name"]) # Asha
print(student.get("city")) # None, no KeyError
print(student.get("city", "NA")) # NA, your own default
Q10. What is a set and when do you use it?
A set is an unordered collection of unique items. Use it to remove duplicates and for fast membership checks (x in my_set).
Q11. What is the difference between append() and extend()?
a = [1, 2]
a.append([3, 4])
print(a) # [1, 2, [3, 4]]
b = [1, 2]
b.extend([3, 4])
print(b) # [1, 2, 3, 4]
Q12. What is a KeyError and how do you avoid it?
It happens when you read a dictionary key that does not exist. Avoid it with .get(), with if key in d, or by catching it with try/except KeyError.
Q13. What is a list comprehension?
A short way to build a list from a loop, with an optional condition.
print([x * x for x in range(1, 6) if x % 2 == 1])
# [1, 9, 25]
Q14. How does slicing work?
The pattern is seq[start:stop:step]. The stop index is not included, and negative indexes count from the end.
s = "PYTHON"
print(s[0:3]) # PYT
print(s[-1]) # N
print(s[::2]) # PTO
print(s[::-1]) # NOHTYP
Q15. How do split() and join() work?
split() breaks a string into a list. join() joins a list of strings into one string.
print("a,b,c".split(",")) # ['a', 'b', 'c']
print("-".join(["a", "b"])) # a-b
Q16. What is the difference between a shallow copy and a deep copy?
A shallow copy copies the outer list but still shares the inner objects. A deep copy copies everything, so the two are fully independent.
import copy
orig = [[1, 2], [3, 4]]
sh = copy.copy(orig)
dp = copy.deepcopy(orig)
orig[0][0] = 99
print(sh[0][0]) # 99
print(dp[0][0]) # 1
Q17. How do you remove duplicates from a list and keep the order?
print(list(dict.fromkeys([3, 1, 3, 2, 1])))
# [3, 1, 2]
Using set() also removes duplicates, but it does not keep the order.
Q18. What is the difference between sort() and sorted()?
sort() changes the list in place and returns None. sorted() returns a new list and leaves the original alone.
nums = [3, 1, 2]
print(sorted(nums), nums)
# [1, 2, 3] [3, 1, 2]
r = nums.sort()
print(r, nums)
# None [1, 2, 3]
Interviewer may ask: what does nums = nums.sort() do? It sets nums to None, a very common beginner bug.
Part 3: Functions and Scope (Q19–Q26)
Q19. What are *args and **kwargs?
*args collects extra positional arguments into a tuple. **kwargs collects extra keyword arguments into a dictionary.
def show(*args, **kwargs):
print(args, kwargs)
show(1, 2, name="Asha", age=20)
# (1, 2) {'name': 'Asha', 'age': 20}
Q20. What is a lambda function?
A small anonymous function written in one line. It is useful for short jobs, mostly with map, filter and sorted.
sq = lambda x: x * x
print(sq(4)) # 16
print(list(map(lambda x: x * 2, [1, 2, 3])))
# [2, 4, 6]
print(list(filter(lambda x: x % 2 == 0, [1, 2, 3, 4])))
# [2, 4]
Q21. What is the difference between map(), filter() and a list comprehension?
map() changes every item. filter() keeps only items that pass a test. A list comprehension can do both in one readable line, and most Python developers prefer it.
Q22. What is the mutable default argument trap?
A default value like [] is created once, when the function is defined, and is shared between calls. This is the most famous Python trick question.
def bad(item, bucket=[]):
bucket.append(item)
return bucket
print(bad(1), bad(2))
def good(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(good(1), good(2))
Practising these questions on your own?
Get hands-on Python training, projects and interview preparation at Skill Hives.
Q23. What is the LEGB rule?
Python looks for a name in this order: Local, Enclosing function, Global, Built-in.
x = "global"
def outer():
x = "enclosing"
def inner():
return x
return inner()
print(outer()) # enclosing
Q24. What do global and nonlocal do?
global lets a function change a module-level variable. nonlocal lets an inner function change a variable of the outer function.
count = 0
def inc():
global count
count += 1
inc()
inc()
print(count) # 2
def make_counter():
n = 0
def step():
nonlocal n
n += 1
return n
return step
c1 = make_counter()
c1()
print(c1()) # 2
Q25. What is a decorator?
A function that takes another function and adds behaviour to it without changing its code. You apply it with @name above the function.
def timer(func):
def wrapper(*a, **k):
res = func(*a, **k)
print("done:", func.__name__)
return res
return wrapper
@timer
def add(a, b):
return a + b
print(add(2, 3))
Q26. What is a generator and why use it?
A generator makes values one at a time with yield, instead of building the whole list in memory. It is ideal for large data.
def countdown(n):
while n > 0:
yield n
n -= 1
print(list(countdown(3)))
# [3, 2, 1]
Interviewer may ask: what is the difference between return and yield? return ends the function. yield pauses it and resumes from the same place on the next request.
Part 4: Object-Oriented Programming (Q27–Q33)
Q27. What are the four pillars of OOP?
Encapsulation (hide data inside a class), inheritance (a child class reuses a parent class), polymorphism (the same method name behaves differently in different classes) and abstraction (show what an object does, hide how).
Q28. What are self and init?
__init__ is the constructor: it runs when you create an object. self is the object itself, and Python passes it explicitly so you can reach the object’s data.
Q29. How does inheritance and method overriding work?
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return "..."
class Dog(Animal):
def speak(self):
return "Woof"
d = Dog("Tommy")
print(d.speak()) # Woof
Q30. What is the difference between str and repr?
__str__ gives a readable text for users (used by print). __repr__ gives an exact, developer-friendly text, ideally one that could recreate the object.
Q31. What is multiple inheritance and MRO?
A class can have more than one parent. MRO (Method Resolution Order) is the order Python searches the parents for a method. You can see it with ClassName.__mro__.
class A:
def hi(self): return "A"
class B(A):
def hi(self): return "B"
class C(A):
def hi(self): return "C"
class D(B, C):
pass
print(D().hi())
print([k.__name__ for k in D.__mro__])
Q32. What is the difference between @classmethod, @staticmethod and an instance method?
An instance method gets self and works on one object. A class method gets cls and works on the class, often to build objects another way. A static method gets neither and is just a function placed inside the class.
class Date:
def __init__(self, y, m, d):
self.y, self.m, self.d = y, m, d
@classmethod
def from_string(cls, s):
y, m, d = map(int, s.split("-"))
return cls(y, m, d)
@staticmethod
def is_leap(y):
return y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)
dt = Date.from_string("2026-10-13")
print(dt.y, dt.m, dt.d)
print(Date.is_leap(2024))
Q33. Does Python have private variables?
Not truly. A single underscore (_x) is only a hint to other developers. A double underscore (__x) triggers name mangling, which makes the name harder to reach but not impossible.
class Account:
def __init__(self):
self.__balance = 100
acct = Account()
# acct.__balance -> AttributeError
print(acct._Account__balance) # 100
Part 5: Errors, Files, Memory and Core Concepts (Q34–Q40)
Q34. How does exception handling work?
Put risky code in try. Handle the error in except. else runs only if no error happened. finally always runs, so use it for cleanup.
def divide(a, b):
try:
r = a / b
except ZeroDivisionError:
print("cannot divide by zero")
else:
print("result", r)
finally:
print("always runs")
divide(4, 2)
divide(4, 0)
Q35. How do you read a file, and why use with?
The with statement closes the file for you, even if an error happens, so you cannot forget to close it.
with open("notes.txt", "r") as f:
for line in f:
print(line.strip())
Q36. How do you raise your own error?
Use raise. For a custom error, make a class that inherits from Exception.
class AgeError(Exception):
pass
def set_age(age):
if age < 0:
raise AgeError("age cannot be negative")
return age
Q37. How does Python manage memory?
Python keeps all objects in a private heap. Each object has a reference count. When the count reaches zero, the memory is freed. A garbage collector also cleans up reference cycles, where two objects point to each other and the count never reaches zero.
Q38. What is the GIL?
The Global Interpreter Lock lets only one thread run Python bytecode at a time in standard CPython. So threads do not speed up CPU-heavy work. Use multiprocessing for that. Threads still help for waiting jobs such as network calls and file reads.
Q39. What is the difference between an iterable and an iterator?
An iterable (list, str, dict) can be looped over. An iterator is the object that gives the next value, one by one, using next(). It raises StopIteration when finished.
it = iter([1, 2])
print(next(it)) # 1
print(next(it)) # 2
next(it) # raises StopIteration
Q40. What does if __name__ == “__main__”: do?
It runs the code below it only when the file is run directly, not when another file imports it. This lets one file work both as a program and as a reusable module.
def main():
print("running")
if __name__ == "__main__":
main()
Interview Process
Most IT companies in India follow a similar multi-round pattern, though the exact rounds vary by company. A typical process, as described for Infosys, looks like this:
| Round | What Is Tested |
|---|---|
| 1. Online assessment | Aptitude, logical reasoning, verbal ability and a coding section |
| 2. Technical interview | Python concepts, data structures, algorithms, databases, operating systems, and your projects or internships |
| 3. Managerial interview | Case studies, hypothetical project situations, decision-making, team fit |
| 4. HR interview | Communication, career goals, why you want to join, relocation, salary expectation |
Platforms commonly recommended for practice include HackerRank, LeetCode, AMCAT and CoCubes.
10 Extra Python Interview Questions
E1. What is a context manager?
An object that sets something up and cleans it up automatically, used with with. Files, database connections and locks use it. You can write one with __enter__ and __exit__, or with contextlib.contextmanager.
E2. What is a virtual environment and why use one?
An isolated folder with its own Python packages, so one project’s library versions do not clash with another’s. Create one with python -m venv env.
E3. What is the difference between a module and a package?
A module is one .py file. A package is a folder of modules, usually with an __init__.py file.
E4. What is the difference between Django and Flask?
Django is a full framework with an ORM, admin panel and authentication built in. Flask is a small, flexible micro-framework where you pick the extra parts yourself.
E5. What is the difference between NumPy and pandas?
NumPy gives fast arrays for numeric maths. pandas builds on it and adds labelled tables (DataFrames) for cleaning and analysing data.
E6. What is the difference between loc and iloc in pandas?
loc selects by label. iloc selects by integer position.
E7. What is monkey patching?
Changing a class or module while the program runs, for example replacing a function for testing. It is powerful but can make code hard to understand.
E8. What is range vs xrange?
xrange is a Python 2 name that some interviewers still ask about. In Python 3 only range exists, and it gives a lazy sequence, not a full list.
E9. How do you debug and log in Python?
Use print for quick checks, the pdb debugger to step through code, and the logging module with levels (DEBUG, INFO, WARNING, ERROR) for real programs.
E10. How do you write a unit test?
Use the built-in unittest module or pytest. Write small functions that call your code and assert the expected result.
Want mentor guidance for your placement interviews?
Skill Hives helps students build projects, practise questions and prepare for interviews.
Salary Context for Indian Freshers
Figures differ by source, so treat these as a range, not one number.
| Source | Fresher | Mid Level | Experienced |
|---|---|---|---|
| Internshala (Infosys page) | ₹3.5–5 LPA | ₹6–10 LPA (2–4 years) | ₹12–25 LPA or more (5+ years) |
| WSCube Tech, updated 14 September 2026, from AmbitionBox | ₹3.0 LPA average (0–1 year) | ₹4.1 LPA (2–3 years) | ₹8.2 LPA (4–9 years) |
Pay also varies by city and skills. Gurgaon, Mumbai, Noida, Bengaluru, Chennai, Pune and Hyderabad are listed as the highest-paying cities, and skills such as Django, Flask, FastAPI, NumPy, pandas, Git and databases can raise pay. These are not guarantees.
Bonus: Four Coding Questions to Practise
Most interviews end with a small coding task. Write these by hand first, then compare.
1. Count word frequency
from collections import Counter
text = "the cat and the hat and the bat"
print(Counter(text.split()).most_common(2))
# [('the', 3), ('and', 2)]
2. Check a palindrome
def is_pal(s):
s = "".join(ch.lower() for ch in s if ch.isalnum())
return s == s[::-1]
print(is_pal("A man, a plan, a canal: Panama"))
# True
3. Fibonacci with a generator
def fib(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
print(list(fib(8)))
# [0, 1, 1, 2, 3, 5, 8, 13]
4. FizzBuzz
print([
"FizzBuzz" if i % 15 == 0
else "Fizz" if i % 3 == 0
else "Buzz" if i % 5 == 0
else i
for i in range(1, 16)
])
How to Use This List: A 7-Day Plan from Skill Hives
- Days 1–2: Part 1 and Part 2. Type every code sample yourself and change one value to see what happens.
- Days 3–4: Part 3 and Part 4. Explain decorators, generators and self out loud, as if teaching a friend.
- Day 5: Part 5, then the four coding questions without looking at the answers.
- Day 6: Ask a friend to quiz you on random questions, or record yourself answering.
- Day 7: Revise only the questions you got wrong.
Interview Tips That Matter More Than the Answers
- Start with a one-line definition, then give a small example. Interviewers value clear, short answers.
- If you do not know, say what you do know and how you would find out. Guessing wildly counts against you.
- Think aloud while you code. Interviewers score your approach, not only the output.
- Know your own resume. Any project you list can be asked about in detail.
Keep Learning with Skill Hives
Skill Hives helps students turn Python basics into job-ready skills. Practise these questions, build small projects and revisit the topics that feel weak. Bookmark this page and share it with a classmate who is preparing for placements.
Ready to go from Python basics to real projects?
Join Skill Hives for practical Python training, mentor support and interview preparation.
FAQ
How many Python questions should I prepare for a fresher interview?
The 40 above cover the core areas that fresher and entry-level rounds test. Understanding them well matters more than memorising a longer list.
Do I need to know advanced topics like async or metaclasses?
Rarely for a first job. Learn them after you are confident with Parts 1 to 5.
Are the code samples tested?
Yes. We ran them and checked the outputs shown in the comments before publishing.