This guide organizes the most frequently asked Python interview questions into 21 topic groups so you can revise in order or jump straight to a weak spot using the table of contents. Every question includes a short answer, a runnable example, its output, and a one-line explanation of why the output is what it is.
Python Basics
Q1. What is Python and why is it popular for interviews?
EasyAnswer: Python is a high-level, interpreted, dynamically-typed language known for readable syntax and a large standard library. It's popular in interviews because its concise syntax lets candidates focus on logic instead of boilerplate.
print("Hello, Interview!")
Output
Hello, Interview!
Explanation: print() writes the
string to standard output followed by a newline.
Q2. Is Python compiled or interpreted?
EasyAnswer: Python source code is first compiled to bytecode (.pyc),
which the Python Virtual Machine then interprets line by line. So it's technically both
compiled and interpreted, but from a developer's view it behaves like an interpreted language.
Q3. What is PEP 8?
EasyAnswer: PEP 8 is Python's official style guide — it covers naming
conventions, indentation (4 spaces), line length, and import ordering, and most teams
enforce it with linters like flake8 or ruff.
Variables
Q4. How does variable assignment work in Python?
EasyAnswer: A Python variable is a name bound to an object in memory — it doesn't hold the value directly like in C, it holds a reference to the object.
a = [1, 2, 3]
b = a
b.append(4)
print(a)
Output
[1, 2, 3, 4]
Explanation: b references the same
list object as a, so mutating b also changes a.
Q5. What's the difference between local and global variables?
EasyAnswer: A local variable is defined inside a function and only exists during that call; a global variable is defined at module level and accessible everywhere, unless shadowed inside a function scope.
Data Types
Q6. What are Python's built-in data types?
EasyAnswer: The core built-in types are int, float,
complex, bool, str, list, tuple,
dict, set, and NoneType.
| Type | Mutable? | Example |
|---|---|---|
| list | Yes | [1, 2, 3] |
| tuple | No | (1, 2, 3) |
| dict | Yes | {"a": 1} |
| set | Yes | {1, 2, 3} |
Q7. How do you check the type of a variable?
Easyx = 3.14
print(type(x))
print(isinstance(x, float))
Output
<class 'float'> True
Operators
Q8. What's the difference between == and is?
Medium
Answer: == compares values for equality, while
is compares object identity (whether both names point to the same
object in memory).
a = [1, 2]
b = [1, 2]
print(a == b)
print(a is b)
Output
True False
Explanation: a and b
hold equal values but are two distinct list objects.
Q9. What does the // operator do?
Easy
Answer: It performs floor division, returning the largest integer
less than or equal to the result — 7 // 2 gives 3.
Loops
Q10. What's the difference between break, continue and pass?
Easy
Answer: break exits the loop entirely, continue
skips to the next iteration, and pass does nothing — it's a syntactic
placeholder.
Q11. What does the else clause on a for loop do?
Medium
for i in range(3):
print(i)
else:
print("loop finished")
Output
0 1 2 loop finished
Explanation: The else block runs
only if the loop completes without hitting a break.
Functions
Q12. What's the difference between *args and **kwargs?
Medium
Answer: *args collects extra positional arguments into
a tuple, and **kwargs collects extra keyword arguments into a dictionary.
def demo(*args, **kwargs):
print(args)
print(kwargs)
demo(1, 2, name="Ankit")
Output
(1, 2)
{'name': 'Ankit'}
Q13. Why is a mutable default argument dangerous?
Harddef add_item(item, bucket=[]):
bucket.append(item)
return bucket
print(add_item("a"))
print(add_item("b"))
Output
['a'] ['a', 'b']
Explanation: The default list is created once
at function definition time and reused across calls, so it silently accumulates state.
Use bucket=None and create a new list inside the function instead.
Strings
Q14. How do you reverse a string in Python?
Easys = "ankit"
print(s[::-1])
Output
tikna
Q15. Are Python strings mutable?
EasyAnswer: No, strings are immutable — any operation that appears to modify a string actually creates and returns a new string object.
Lists
Q16. What's the time complexity of common list operations?
Medium| Operation | Complexity |
|---|---|
Index access lst[i] | O(1) |
Append lst.append(x) | O(1) amortized |
Insert at index lst.insert(0, x) | O(n) |
Search x in lst | O(n) |
Q17. How do you remove duplicates from a list while keeping order?
Mediumnums = [3, 1, 3, 2, 1, 4]
unique = list(dict.fromkeys(nums))
print(unique)
Output
[3, 1, 2, 4]
Explanation: Dictionaries preserve insertion
order in Python 3.7+, so dict.fromkeys() is a clean order-preserving
dedupe trick.
Tuples
Q18. Why would you use a tuple instead of a list?
EasyAnswer: Tuples are immutable, so they're hashable (usable as dict keys or set members), slightly faster to iterate, and communicate intent — "this collection shouldn't change."
Q19. How do you unpack a tuple with extra elements?
Mediumfirst, *middle, last = (1, 2, 3, 4, 5)
print(first, middle, last)
Output
1 [2, 3, 4] 5
Dictionary
Q20. How do you safely get a key that might not exist?
Easyconfig = {"debug": True}
print(config.get("timeout", 30))
Output
30
Explanation: .get() avoids a
KeyError by returning a default value when the key is missing.
Q21. What is a dictionary comprehension?
Mediumsquares = {n: n**2 for n in range(5)}
print(squares)
Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Sets
Q22. How do you find common elements between two lists efficiently?
Mediuma = [1, 2, 3, 4]
b = [3, 4, 5, 6]
print(set(a) & set(b))
Output
{3, 4}
Explanation: Converting to sets and using
& (intersection) is O(min(len(a), len(b))) — much faster than a
nested loop for large inputs.
OOP
Q23. What are the four pillars of OOP in Python?
MediumAnswer: Encapsulation (bundling data and methods), Abstraction (hiding implementation detail), Inheritance (reusing behaviour from a parent class), and Polymorphism (one interface, many implementations).
Q24. What's the difference between a class method, a static method and an instance method?
Mediumclass Demo:
def instance_method(self):
return "uses self"
@classmethod
def class_method(cls):
return "uses cls"
@staticmethod
def static_method():
return "uses neither"
Explanation: Instance methods access object
state via self, class methods access class state via cls,
and static methods are just namespaced functions with no automatic first argument.
Inheritance
Q25. How does super() work in single inheritance?
Medium
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name)
self.breed = breed
d = Dog("Bruno", "Labrador")
print(d.name, d.breed)
Output
Bruno Labrador
Q26. What is the Method Resolution Order (MRO)?
HardAnswer: MRO is the order Python follows to look up a method across
a chain of parent classes in multiple inheritance, computed using the C3 linearization
algorithm and inspectable via ClassName.__mro__.
Polymorphism
Q27. What is duck typing?
MediumAnswer: "If it walks like a duck and quacks like a duck, it's a duck" — Python doesn't check an object's type before calling a method, only whether the method exists, which enables polymorphism without shared inheritance.
class Cat:
def speak(self): return "Meow"
class Duck:
def speak(self): return "Quack"
for animal in [Cat(), Duck()]:
print(animal.speak())
Output
Meow Quack
Exception Handling
Q28. What's the difference between except Exception and a bare except:?
Medium
Answer: A bare except: catches everything, including
KeyboardInterrupt and SystemExit, which can hide bugs and
block clean shutdowns. except Exception catches normal errors only and
is the safer default.
Q29. What does the finally block guarantee?
Easy
try:
1 / 0
except ZeroDivisionError:
print("caught it")
finally:
print("always runs")
Output
caught it always runs
File Handling
Q30. Why should you use with open(...) instead of open() directly?
Easy
with open("notes.txt", "w") as f:
f.write("Interview prep")
Explanation: The with statement
uses a context manager that automatically closes the file — even if an exception is
raised inside the block — preventing file-handle leaks.
Modules
Q31. What does if __name__ == "__main__": do?
Medium
Answer: __name__ equals "__main__" only
when the file is run directly, not when it's imported as a module — this guard lets
you write both a reusable module and a runnable script in the same file.
Decorators
Q32. How do you write a simple timing decorator?
Hardimport time
from functools import wraps
def timer(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = time.perf_counter()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.perf_counter()-start:.4f}s")
return result
return wrapper
@timer
def slow_add(a, b):
return a + b
slow_add(2, 3)
Explanation: A decorator is a function that
wraps another function to add behaviour without changing its source code;
@wraps preserves the original function's name and docstring.
Generators
Q33. Why use a generator instead of returning a list?
Mediumdef even_numbers(limit):
for n in range(limit):
if n % 2 == 0:
yield n
for num in even_numbers(6):
print(num)
Output
0 2 4
Explanation: yield pauses the
function and returns one value at a time, so the whole sequence is never held in
memory at once — critical for very large or infinite sequences.
Iterators
Q34. What's the difference between an iterable and an iterator?
MediumAnswer: An iterable implements __iter__() and can
produce an iterator (e.g. a list); an iterator implements both __iter__()
and __next__() and tracks its own iteration state.
NumPy
Q35. Why are NumPy arrays faster than Python lists?
MediumAnswer: NumPy arrays store elements in contiguous memory with a single fixed type and push loops down into optimized C code (vectorization), avoiding the per-element overhead of Python's dynamic typing.
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr * 2)
Output
[2 4 6 8]
Pandas
Q36. What's the difference between loc and iloc?
Medium
Answer: .loc[] selects rows and columns by label,
while .iloc[] selects by integer position — mixing them up is one of the
most common Pandas interview traps.
import pandas as pd
df = pd.DataFrame({"name": ["A", "B"], "score": [90, 85]})
print(df.loc[0, "name"])
print(df.iloc[0, 1])
Output
A 90
Q37. How do you handle missing values in a DataFrame?
MediumAnswer: Use df.isnull().sum() to find them, then
either drop rows/columns with df.dropna() or fill values with
df.fillna(value) depending on whether the missingness is random.
Interview Tips
- Think out loud — interviewers grade your reasoning, not just the final answer.
- Start with the brute-force solution, then optimize once it works.
- Always mention time and space complexity, even if not asked directly.
- If you're stuck, ask a clarifying question instead of guessing silently.
- Re-read the question after coding to catch edge cases like empty input.
💬 Comments coming soon