Top 100 Python Interview Questions & Answers for Beginners, Intermediate, and Advanced


Prepare for Python developer interviews with 100 essential questions and answers. Covers basics, OOP, data structures, libraries, web development, automation, and advanced Python concepts.

Q1: What is Python and what are its key features?

Answer: Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum in 1991. Key features:

  1. Simple and easy to learn
  2. Interpreted
  3. Dynamically typed
  4. Object-Oriented & Procedural
  5. Large standard library
  6. Cross-platform
  7. Open-source

Q2: What are Python’s data types?

Answer: Python has several built-in data types:

  1. Numeric types: int, float, complex
  2. Sequence types: list, tuple, range
  3. Text type: str
  4. Mapping type: dict
  5. Set types: set, frozenset
  6. Boolean type: bool
  7. Binary types: bytes, bytearray, memoryview

Q3: What is the difference between list and tuple?

Answer:

  1. List: mutable, allows modification
  2. Tuple: immutable, cannot be modified
  3. Example:

my_list = [1, 2, 3]
my_list[0] = 10 # Works

my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # Error

Q4: What are mutable and immutable objects in Python?

Answer:

  1. Mutable: Objects that can change (list, dict, set)
  2. Immutable: Objects that cannot change (int, float, str, tuple)

Q5: What is Python’s difference between shallow copy and deep copy?

Answer:

  1. Shallow copy: copies the object but nested objects are shared
  2. Deep copy: copies the object and all nested objects
  3. Example:

import copy
list1 = [[1,2],[3,4]]
shallow = copy.copy(list1)
deep = copy.deepcopy(list1)
list1[0][0] = 10
print(shallow) # [[10,2],[3,4]]
print(deep) # [[1,2],[3,4]]

Q6: Difference between Python 2 and Python 3?

Answer:

  1. Print statement: Python 2 → print "Hi", Python 3 → print("Hi")
  2. Integer division: Python 2 truncates by default, Python 3 returns float
  3. Unicode: Python 3 uses Unicode strings by default

Q7: Explain Python memory management.

Answer: Python uses private heap space for memory allocation and has a garbage collector to free unreferenced memory.

Q8: What are Python decorators?

Answer: Functions that modify the behavior of another function.

Example:


def decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper

@decorator
def say_hello():
print("Hello!")

say_hello()

Q9: What is GIL (Global Interpreter Lock)?

Answer: A mutex in Python that allows only one thread to execute at a time. Limits CPU-bound multi-threading.

Q10: Explain *args and **kwargs.

Answer:

  1. *args → collects positional arguments as a tuple
  2. **kwargs → collects keyword arguments as a dictionary
  3. Example:

def func(*args, **kwargs):
print(args)
print(kwargs)

func(1,2,3, a=4, b=5)

Q11: What are Python modules and packages?

Answer:

  1. Module: A .py file containing Python code
  2. Package: A folder with __init__.py containing modules

Q12: What is Python’s difference between is and ==?

Answer:

  1. is → checks object identity (same memory location)
  2. == → checks value equality

Q13: What are Python’s numbers types?

Answer: int, float, complex.

Example:


x = 10 # int
y = 10.5 # float
z = 2+3j # complex

Q14: Difference between append() and extend() in list?

Answer:

  1. append() → adds single element
  2. extend() → adds multiple elements from iterable

lst = [1,2]
lst.append([3,4]) # [1,2,[3,4]]
lst.extend([5,6]) # [1,2,[3,4],5,6]

Q15: How to handle exceptions in Python?

Answer: Use try-except blocks.


try:
x = 1/0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Execution done")

Q16: What are Python’s string methods?

Answer: Common methods: lower(), upper(), split(), replace(), strip(), join()

Q17: What is Python’s difference between remove(), pop() and del?

Answer:

  1. remove(value) → removes first occurrence
  2. pop(index) → removes element at index and returns it
  3. del → deletes element or variable entirely

Q18: What are Python’s list comprehensions?

Answer: A concise way to create lists.


squares = [x**2 for x in range(5)]
print(squares) # [0,1,4,9,16]

Q19: Difference between range() and xrange()?

Answer:

  1. Python 2: range() returns list, xrange() returns generator
  2. Python 3: range() behaves like xrange()

Q20: Explain Python’s pass statement.

Answer: pass is a null operation, used as a placeholder.


def func():
pass

Q21: What are Python’s boolean operators?

Answer: and, or, not


x = True
y = False
print(x and y) # False
print(x or y) # True
print(not x) # False

Q22: What are Python’s file handling modes?

Answer:

  1. r → read
  2. w → write
  3. a → append
  4. rb → read binary
  5. wb → write binary

Q23: How to open and read a file in Python?


with open("file.txt", "r") as f:
content = f.read()
print(content)

Q24: What is Python’s difference between is and ==?

Answer:

  1. is → object identity
  2. == → value equality

Q25: How to convert string to int in Python?


s = "100"
num = int(s)
print(num) # 100


Q26: What are Python’s functions?

Answer: Functions are reusable blocks of code that perform a specific task.


def add(a, b):
return a + b

print(add(2, 3)) # 5

Q27: Explain Python’s lambda functions.

Answer: Anonymous, single-line functions defined using lambda.


square = lambda x: x**2
print(square(5)) # 25

Q28: What is Python’s map() function?

Answer: Applies a function to all items in an iterable.


nums = [1,2,3]
squared = list(map(lambda x: x**2, nums))
print(squared) # [1,4,9]

Q29: What is Python’s filter() function?

Answer: Filters items based on a function returning True or False.


nums = [1,2,3,4,5]
even = list(filter(lambda x: x%2==0, nums))
print(even) # [2,4]

Q30: What is Python’s reduce() function?

Answer: Reduces an iterable to a single value using a function.


from functools import reduce
nums = [1,2,3,4]
sum_all = reduce(lambda x,y: x+y, nums)
print(sum_all) # 10

Q31: Explain Python’s generators.

Answer: Functions that yield values one at a time using yield instead of return.


def gen():
for i in range(3):
yield i

for val in gen():
print(val)

Q32: What are Python’s iterators?

Answer: Objects that can be iterated using next().


lst = [1,2,3]
it = iter(lst)
print(next(it)) # 1
print(next(it)) # 2

Q33: What is Python’s difference between deep copy and shallow copy?

Answer: Already explained in Q5. Shallow copies only top-level object; deep copies all nested objects.

Q34: What are Python’s OOP concepts?

Answer:

  1. Class & Object
  2. Inheritance
  3. Polymorphism
  4. Encapsulation
  5. Abstraction

Q35: How to create a class and object in Python?


class Person:
def __init__(self, name):
self.name = name

p = Person("John")
print(p.name) # John

Q36: What is Python’s inheritance?

Answer: Mechanism to derive a class from another class.


class Parent:
def greet(self):
print("Hello")

class Child(Parent):
pass

c = Child()
c.greet() # Hello

Q37: What is Python’s polymorphism?

Answer: Ability to take many forms; same function name behaves differently.


print(len("Hello")) # 5
print(len([1,2,3])) # 3

Q38: What is Python’s encapsulation?

Answer: Restrict access to methods and variables using private attributes (_var, __var).

Q39: What is Python’s abstraction?

Answer: Hiding complex implementation using abstract classes and methods.


from abc import ABC, abstractmethod

class Shape(ABC):
@abstractmethod
def area(self):
pass

Q40: Difference between Python class method, instance method, and static method?

Answer:

  1. Instance method: operates on object instance
  2. Class method: operates on class (@classmethod)
  3. Static method: independent, no self or cls

Q41: Explain Python’s with statement.

Answer: Simplifies resource management; automatically closes resources.


with open("file.txt") as f:
data = f.read()

Q42: What is Python’s __init__ method?

Answer: Constructor method called when an object is created.

Q43: What are Python’s modules and packages?

Answer: Already explained in Q11. Modules = .py files, Packages = folders with __init__.py.

Q44: Difference between del and remove()?

Answer:

  1. del → deletes variable or element by index
  2. remove() → deletes element by value

Q45: What are Python’s built-in data structures?

Answer: list, tuple, dict, set, frozenset, deque

Q46: Difference between set and frozenset?

Answer:

  1. set → mutable
  2. frozenset → immutable

Q47: Difference between is and ==?

Answer: Already explained in Q12.

Q48: How to sort a list in Python?


lst = [3,1,2]
lst.sort()
print(lst) # [1,2,3]

Q49: How to reverse a list in Python?


lst = [1,2,3]
lst.reverse()
print(lst) # [3,2,1]

Q50: How to merge two dictionaries in Python?


dict1 = {'a':1}
dict2 = {'b':2}
merged = {**dict1, **dict2}
print(merged) # {'a':1, 'b':2}


Q51: What are Python decorators and their use cases?

Answer: Decorators are functions that modify the behavior of another function or method. They are commonly used for logging, authentication, or validation.


def decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper

@decorator
def greet():
print("Hello")

greet()

Q52: Explain the difference between @staticmethod and @classmethod.

Answer:

  1. @staticmethod does not access the class or instance. It behaves like a regular function inside a class.
  2. @classmethod receives the class as the first argument (cls) and can access class variables.

class Example:
@staticmethod
def static_method(): print("Static method")
@classmethod
def class_method(cls): print("Class method")

Example.static_method()
Example.class_method()

Q53: What are Python generators and why are they useful?

Answer: Generators are functions that yield values one at a time using the yield keyword. They are memory-efficient for large datasets.


def gen_numbers(n):
for i in range(n):
yield i

for num in gen_numbers(5):
print(num)

Q54: How do coroutines work in Python?

Answer: Coroutines are asynchronous functions defined with async def. They allow cooperative multitasking with await.


import asyncio

async def say_hello():
print("Hello")
await asyncio.sleep(1)
print("World")

asyncio.run(say_hello())

Q55: What is the difference between multithreading and multiprocessing in Python?

Answer:

  1. Multithreading: Multiple threads share the same memory space; limited by GIL; good for I/O-bound tasks.
  2. Multiprocessing: Separate memory space; true parallelism; good for CPU-bound tasks.

Q56: What is Python’s Global Interpreter Lock (GIL)?

Answer: GIL is a mutex that allows only one thread to execute Python bytecode at a time, which prevents true parallel execution of threads for CPU-bound tasks.

Q57: How do you handle exceptions in Python?

Answer: Use try-except blocks, optionally else for code that runs if no exception occurs, and finally for cleanup.


try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Division successful")
finally:
print("Cleanup done")

Q58: How to profile Python code?

Answer: Use the cProfile module to measure execution time of functions.


import cProfile

def compute():
sum(range(1000000))

cProfile.run("compute()")

Q59: What is Python’s difference between deep copy and shallow copy?

Answer:

  1. Shallow copy: copies the outer object only; nested objects are shared.
  2. Deep copy: copies the object and all nested objects recursively.

import copy
lst = [[1,2],[3,4]]
shallow = copy.copy(lst)
deep = copy.deepcopy(lst)
lst[0][0] = 10
print(shallow) # [[10,2],[3,4]]
print(deep) # [[1,2],[3,4]]

Q60: How to implement a singleton in Python?

Answer: Ensure only one instance exists.


class Singleton:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance

a = Singleton()
b = Singleton()
print(a is b) # True

Q61: How to merge two dictionaries in Python?


dict1 = {'a':1}
dict2 = {'b':2}
merged = {**dict1, **dict2}
print(merged) # {'a':1,'b':2}

Q62: How to remove duplicates from a list in Python?


lst = [1,2,2,3,3,4]
unique = list(set(lst))
print(unique) # [1,2,3,4]

Q63: How to reverse a string in Python?


s = "Python"
reversed_s = s[::-1]
print(reversed_s) # "nohtyP"

Q64: How to sort a dictionary by value?


d = {"a":3, "b":1, "c":2}
sorted_d = dict(sorted(d.items(), key=lambda x: x[1]))
print(sorted_d) # {'b':1,'c':2,'a':3}

Q65: How do Python context managers work?

Answer: Context managers manage resources and guarantee cleanup with __enter__ and __exit__.


class FileManager:
def __init__(self, filename):
self.file = open(filename, 'w')
def __enter__(self):
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()

with FileManager('test.txt') as f:
f.write("Hello World")

Q66: How to use Python’s zip() function?


names = ["Alice","Bob"]
ages = [25,30]
combined = list(zip(names, ages))
print(combined) # [('Alice',25),('Bob',30)]

Q67: How to use Python’s enumerate() function?


lst = ["a","b","c"]
for idx, val in enumerate(lst):
print(idx, val)

Q68: How to apply a function to a Pandas DataFrame column?


import pandas as pd
df = pd.DataFrame({"A":[1,2,3]})
df["B"] = df["A"].apply(lambda x: x**2)
print(df)

Q69: How to handle missing values in Pandas?


import pandas as pd
df = pd.DataFrame({"A":[1,None,3]})
df.fillna(0, inplace=True) # Replace with 0
df.dropna(inplace=True) # Drop rows with NaN

Q70: How to merge two Pandas DataFrames?


import pandas as pd
df1 = pd.DataFrame({"id":[1,2],"val":[10,20]})
df2 = pd.DataFrame({"id":[2,3],"val":[30,40]})
merged = pd.merge(df1, df2, on="id", how="inner")
print(merged)

Q71: How do you use Python’s Counter from collections?


from collections import Counter
lst = [1,2,2,3,3,3]
count = Counter(lst)
print(count) # Counter({3:3,2:2,1:1})

Q72: How to implement Python multithreading?


import threading

def task():
print("Thread running")

t1 = threading.Thread(target=task)
t1.start()
t1.join()

Q73: How to implement Python multiprocessing?


from multiprocessing import Process

def task():
print("Process running")

p = Process(target=task)
p.start()
p.join()

Q74: How to measure execution time of a Python function?


import time

start = time.time()
sum(range(100000))
end = time.time()
print(f"Execution time: {end-start} seconds")

Q75: How to read a large file efficiently in Python?


with open("large_file.txt") as f:
for line in f:
process(line)

Q76: How do you use Python regular expressions?


import re
text = "My number is 1234"
pattern = r"\d+"
match = re.search(pattern, text)
print(match.group()) # 1234

Q77: How to handle JSON in Python?


import json
data = '{"name":"Alice","age":25}'
parsed = json.loads(data)
print(parsed["name"]) # Alice
json_str = json.dumps(parsed)
print(json_str)

Q78: How to use Python’s __str__ and __repr__ methods?


class Test:
def __str__(self): return "User-friendly"
def __repr__(self): return "Developer-friendly"

t = Test()
print(t) # User-friendly
print(repr(t)) # Developer-friendly

Q79: How to create a Python virtual environment?


python -m venv myenv
source myenv/bin/activate # Linux/Mac
myenv\Scripts\activate # Windows
deactivate # exit environment

Q80: How to implement Python property decorators?


class Person:
def __init__(self, name):
self._name = name

@property
def name(self):
return self._name

@name.setter
def name(self, value):
self._name = value

p = Person("Alice")
p.name = "Bob"
print(p.name) # Bob

Q81: How to reverse a list in Python?


lst = [1,2,3]
lst.reverse()
print(lst) # [3,2,1]

Q82: How to remove an element from a list by index?


lst = [1,2,3]
del lst[1]
print(lst) # [1,3]

Q83: How to remove an element from a list by value?


lst = [1,2,3,2]
lst.remove(2)
print(lst) # [1,3,2]

Q84: How to create a Python module?

Answer: Create a .py file and import it in another script.


# mymodule.py
def greet(): print("Hello")

# main.py
import mymodule
mymodule.greet()

Q85: How to handle multiple exceptions in Python?


try:
x = int("abc")
except (ValueError, TypeError) as e:
print(f"Error: {e}")

Q86: How to implement Python logging?


import logging
logging.basicConfig(level=logging.INFO)
logging.info("This is info message")
logging.error("This is error message")

Q87: How to check Python version in code?


import sys
print(sys.version)

Q88: How to find all unique elements in a list?


lst = [1,2,2,3,3,4]
unique = list(set(lst))
print(unique)

Q89: How to merge two lists in Python?


list1 = [1,2]
list2 = [3,4]
merged = list1 + list2
print(merged) # [1,2,3,4]

Q90: How to find the length of a list, string, or dictionary?


lst = [1,2,3]
s = "Python"
d = {"a":1,"b":2}
print(len(lst), len(s), len(d)) # 3 6 2

Q91: How to use Python’s any() and all()?


lst = [True, False, True]
print(any(lst)) # True
print(all(lst)) # False

Q92: How to use Python’s map() function?


nums = [1,2,3]
squared = list(map(lambda x: x**2, nums))
print(squared) # [1,4,9]

Q93: How to use Python’s filter() function?


nums = [1,2,3,4]
even = list(filter(lambda x: x%2==0, nums))
print(even) # [2,4]

Q94: How to use Python’s reduce() function?


from functools import reduce
nums = [1,2,3,4]
sum_all = reduce(lambda x,y: x+y, nums)
print(sum_all) # 10

Q95: How to implement Python recursion?


def factorial(n):
if n==0:
return 1
return n*factorial(n-1)

print(factorial(5)) # 120

Q96: How to check if a string is a palindrome?


s = "radar"
if s == s[::-1]:
print("Palindrome")
else:
print("Not palindrome")

Q97: How to flatten a nested list in Python?


nested = [[1,2],[3,4]]
flat = [item for sublist in nested for item in sublist]
print(flat) # [1,2,3,4]

Q98: How to copy a list in Python?


lst1 = [1,2,3]
lst2 = lst1.copy()
print(lst2) # [1,2,3]

Q99: How to check if a key exists in a dictionary?


d = {"a":1,"b":2}
print("a" in d) # True
print(d.get("c")) # None

Q100: How to sort a list of dictionaries by a key?


data = [{"name":"Alice","age":25},{"name":"Bob","age":20}]
sorted_data = sorted(data, key=lambda x: x["age"])
print(sorted_data)