Python Interview Questions and Answers
Python Interview Questions and Answers
What is Python?
Answer:
Python is a high-level, interpreted, object-oriented programming language known for its readability and simplicity. It supports multiple programming paradigms like procedural, object-oriented, and functional programming.
What are the key features of Python?
Answer:
-
Easy to learn and read
-
Interpreted language
-
Dynamically typed
-
Large standard library
-
Cross-platform support
-
Supports OOP and functional programming
What is the difference between list and tuple?
Answer:
| List | Tuple |
|---|---|
| Mutable | Immutable |
Uses [] | Uses () |
| Slower | Faster |
| Can be modified | Cannot be modified |
Example:
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
What is the difference between == and is?
Answer:
-
==checks value equality -
ischecks memory location (identity)
Example:
a = [1,2]
b = [1,2]
print(a == b) # True
print(a is b) # False
What are Python data types?
Answer:
-
int
-
float
-
str
-
list
-
tuple
-
dict
-
set
-
bool
What is a decorator?
Answer:
A decorator is a function that modifies the behavior of another function without changing its code.
Example:
def decorator(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper
@decorator
def greet():
print("Hello")
greet()
What is the difference between deepcopy and copy?
Answer:
-
copy()→ Creates shallow copy (nested objects share reference) -
deepcopy()→ Creates complete independent copy
What is list comprehension?
Answer:
A concise way to create lists.
Example:
squares = [x**2 for x in range(5)]
What is a lambda function?
Answer:
An anonymous function defined using lambda.
Example:
add = lambda a, b: a + b
print(add(2, 3))
What is the difference between *args and **kwargs?
Answer:
-
*args→ Pass multiple positional arguments -
**kwargs→ Pass multiple keyword arguments
Example:
def example(*args, **kwargs):
print(args)
print(kwargs)
What is GIL (Global Interpreter Lock)?
Answer:
GIL is a mutex in CPython that allows only one thread to execute Python bytecode at a time. It prevents true multi-threading in CPU-bound programs.
What are generators?
Answer:
Generators are functions that use yield to return values one at a time, saving memory.
Example:
def gen():
yield 1
yield 2
Difference between append() and extend()?
Answer:
-
append()→ Adds single element -
extend()→ Adds multiple elements
What is exception handling?
Answer:
Handling runtime errors using try, except, finally.
Example:
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
What is the difference between @staticmethod and @classmethod?
Answer:
-
@staticmethod→ No access to class or instance -
@classmethod→ Access to class usingcls
What is Python’s memory management?
Answer:
-
Automatic memory allocation
-
Reference counting
-
Garbage collection
What are Python modules and packages?
Answer:
-
Module → A single Python file
-
Package → Collection of modules in a directory with
__init__.py
What is monkey patching?
Answer:
Modifying a class or module at runtime.
What is the difference between multithreading and multiprocessing?
Answer:
-
Multithreading → Multiple threads, shared memory
-
Multiprocessing → Multiple processes, separate memory
What are common Python interview coding problems?
Answer:
-
Reverse a string
-
Check palindrome
-
Find prime number
-
Remove duplicates
-
Binary search
-
Anagram check
What will be the output?
a = [1, 2, 3]
b = a
b.append(4)
print(a)
Answer:
[1, 2, 3, 4]
Because b references the same list object as a.
What is the output?
print(0.1 + 0.2 == 0.3)
Answer:
False
Due to floating-point precision issues.
Mutable Default Argument Problem
def add_item(item, my_list=[]):
my_list.append(item)
return my_list
print(add_item(1))
print(add_item(2))
Answer:
[1]
[1, 2]
Default list is created only once, not every function call.
What will this print?
x = "Python"
print(x[::-1])
Answer:
nohtyP (String slicing reverse)
Output?
print(bool("False"))
Answer:
True
Any non-empty string is True.
Difference between is and == (Tricky Example)
a = 256
b = 256
print(a is b)
Answer:
True (Small integers are cached)
What happens here?
for i in range(3):
print(i)
i = 5
Answer:
0
1
2
Loop variable reassignment doesn’t affect iteration.
What is the output?
print([i*i for i in range(3)])
Answer:
[0, 1, 4]
What will this return?
def func():
try:
return 1
finally:
return 2
print(func())
Answer:
2
👉 finally overrides return.
What is the output?
a = [1, 2, 3]
print(a * 2)
Answer:
[1, 2, 3, 1, 2, 3]
Mutable Default Argument Trap
Question
What is the output?
def add_item(value, items=[]):
items.append(value)
return items
print(add_item(1))
print(add_item(2))
print(add_item(3))
Answer
[1]
[1, 2]
[1, 2, 3]
Explanation
Default arguments are evaluated only once at function definition time — not each call.
Correct Version
def add_item(value, items=None):
if items is None:
items = []
items.append(value)
return items
Late Binding Closure Problem
Question
funcs = []
for i in range(3):
funcs.append(lambda: i)
print([f() for f in funcs])
Answer
[2, 2, 2]
Why?
Lambdas capture variable by reference, not by value.
Fix
funcs.append(lambda i=i: i)
What Will This Print?
a = [1, 2, 3]
b = a[:]
b[0] = 100
print(a)
Answer
[1, 2, 3]
Explanation
Slicing creates a shallow copy.
Tricky finally Block
def test():
try:
return 10
finally:
return 20
print(test())
Answer
20
finally overrides the return from try.
Deep vs Shallow Copy (Important)
import copy
a = [[1,2],[3,4]]
b = copy.copy(a)
b[0][0] = 100
print(a)
Answer
[[100, 2], [3, 4]]
Shallow copy copies outer list only.
Dictionary Default Value Trap
data = dict.fromkeys(["a", "b"], [])
data["a"].append(1)
print(data)
Answer
{'a': [1], 'b': [1]}
Both keys share same list reference.
Tricky Boolean Logic
print([] == False)
print(bool([]))
Answer
False
False
Empty list is False in boolean context but not equal to False.
Generator vs List (Memory Question)
gen = (x*x for x in range(5))
print(gen)
Answer
It prints a generator object, not values.
Use list(gen) to see values.
Class Variable vs Instance Variable
class Test:
items = []
def add(self, value):
self.items.append(value)
a = Test()
b = Test()
a.add(1)
print(b.items)
Answer
[1]
Class variables are shared across instances.
What is the Output?
print(0.1 + 0.2 == 0.3)
Answer
False
Floating point precision issue.
Comments
Post a Comment