Sarkari Result

India's Most Trusted Education Portal

Latest Jobs Results Admit Cards Answer Keys Current Affairs

🐍 Python Programming Interview Questions 2026

Python Interview Questions, Data structures, Decorators, Generators, and OOPs concepts.

All (20) 🟢 Easy 🟡 Medium 🔴 Hard
1
What are Python's key features?
Easy
  • Easy to read/write: Clean, English-like syntax
  • Interpreted: Executed line by line
  • Dynamically typed: No need to declare variable types
  • Object-Oriented: Supports classes and inheritance
  • Extensive libraries: NumPy, Pandas, Django, Flask, etc.
  • Cross-platform: Runs on Windows, Linux, Mac
  • Free and open source
  • Garbage collected: Automatic memory management
2
What is the difference between list, tuple, set, and dictionary?
Easy
List []
  • Ordered, mutable, allows duplicates
  • Use: General purpose collection


Tuple ()
  • Ordered, immutable, allows duplicates
  • Use: Fixed data, faster than list


Set {}
  • Unordered, mutable, NO duplicates
  • Use: Unique values, set operations


Dictionary {key: value}
  • Unordered (ordered in Python 3.7+), mutable, unique keys
  • Use: Key-value data storage
3
What is a Python decorator? Give an example.
Medium
A decorator is a function that wraps another function to extend its behavior without modifying it.

Syntax: Use @decorator_name above the function.

Example — Timing decorator:
import time

def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"Time: {time.time()-start:.4f}s")
return result
return wrapper

@timer
def slow_func():
time.sleep(1)

slow_func() # Output: Time: 1.0001s
4
What is a Python generator? How is it different from a list?
Medium
A generator is a function that yields values one at a time using yield keyword instead of returning all at once.

Key Differences:
  • List: All values stored in memory at once
  • Generator: Values produced on demand (lazy evaluation)
  • Generator is memory-efficient for large datasets


Example:
def count_up(n):
for i in range(n):
yield i

gen = count_up(1000000) # No memory issue!
next(gen) # 0
next(gen) # 1
5
What is the difference between *args and **kwargs?
Easy
*args (Non-keyword arguments):
  • Accepts variable number of positional arguments
  • Collected as a tuple

def greet(*args):
for name in args:
print(f"Hello {name}")
greet("Alice", "Bob", "Charlie")


**kwargs (Keyword arguments):
  • Accepts variable number of keyword arguments
  • Collected as a dictionary

def info(**kwargs):
for key, val in kwargs.items():
print(f"{key}: {val}")
info(name="Alice", age=25)
6
What are list comprehensions in Python?
Easy
List comprehension is a concise way to create lists in a single line.

Syntax: [expression for item in iterable if condition]

Examples:
# Squares of 0-9
squares = [x**2 for x in range(10)]
# [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# Even numbers only
evens = [x for x in range(20) if x%2==0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

# Nested — flatten matrix
matrix = [[1,2],[3,4],[5,6]]
flat = [num for row in matrix for num in row]
# [1, 2, 3, 4, 5, 6]
7
What is the difference between deep copy and shallow copy?
Medium
Shallow Copy:
  • Creates new object but references same nested objects
  • Changes in nested objects reflect in both
  • Done via: copy.copy() or slice [:]


Deep Copy:
  • Creates completely independent copy including nested objects
  • Changes do NOT affect original
  • Done via: copy.deepcopy()


import copy
original = [[1,2],[3,4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original[0][0] = 99
# shallow[0][0] = 99 (affected!)
# deep[0][0] = 1 (not affected)
8
Explain Python's GIL (Global Interpreter Lock).
Hard
The GIL is a mutex lock in CPython that allows only ONE thread to execute Python bytecode at a time, even on multi-core processors.

Why it exists: Python's memory management (reference counting) is not thread-safe without GIL.

Impact:
  • CPU-bound multi-threaded programs don't benefit from multiple cores
  • I/O-bound programs: GIL released during I/O, so threads DO help


Solutions for CPU-bound tasks:
  • Use multiprocessing module (separate processes)
  • Use Jython or IronPython (no GIL)
  • Use C extensions like NumPy
9
What are Python's magic/dunder methods?
Medium
Magic methods (dunder = double underscore) are special methods that define behavior for built-in operations.

Common Magic Methods:
  • __init__ — Constructor
  • __str__ — String representation (print)
  • __repr__ — Official string representation
  • __len__ — len() function
  • __add__ — + operator
  • __eq__ — == operator
  • __lt__ — < operator


class Vector:
def __init__(self, x, y): self.x, self.y = x, y
def __add__(self, other): return Vector(self.x+other.x, self.y+other.y)
def __str__(self): return f"({self.x}, {self.y})"
10
What is the difference between @staticmethod and @classmethod?
Medium
@staticmethod:
  • Does not receive implicit first argument
  • Cannot access class or instance variables
  • Utility function related to the class

class Math:
@staticmethod
def add(a, b): return a + b
Math.add(2, 3) # 5


@classmethod:
  • Receives class (cls) as first argument
  • Can access/modify class state
  • Used as alternative constructors

class Person:
count = 0
@classmethod
def get_count(cls): return cls.count
11
What is exception handling in Python?
Easy
Keywords: try, except, else, finally, raise

try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Error: {e}")
except (TypeError, ValueError):
print("Type or value error")
else:
print("No error occurred") # runs if no exception
finally:
print("Always runs") # cleanup code


Custom Exception:
class MyError(Exception):
def __init__(self, msg):
super().__init__(msg)

raise MyError("Something went wrong")
12
What is a Python lambda function?
Easy
A lambda is an anonymous (nameless) function defined in a single line using the lambda keyword.

Syntax: lambda arguments: expression

Examples:
# Regular function
def square(x): return x**2

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

# With map()
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
# [1, 4, 9, 16]

# With filter()
evens = list(filter(lambda x: x%2==0, nums))
# [2, 4]
13
What are Python's built-in data types?
Easy
Numeric: int, float, complex
Text: str
Sequence: list, tuple, range
Mapping: dict
Set: set, frozenset
Boolean: bool (True/False)
Binary: bytes, bytearray, memoryview
None: NoneType

Type checking:
x = 42
print(type(x)) #
print(isinstance(x, int)) # True


Type conversion:
str(42) # "42"
int("42") # 42
float(42) # 42.0
list((1,2)) # [1, 2]
14
What is the difference between is and == in Python?
Medium
== (Equality operator):
  • Compares VALUES of two objects
  • Calls __eq__() internally


is (Identity operator):
  • Checks if both refer to SAME object in memory
  • Compares object IDs using id()


Example:
a = [1, 2, 3]
b = [1, 2, 3]
c = a

a == b # True (same values)
a is b # False (different objects)
a is c # True (same object)

# Integer caching (-5 to 256)
x = 256
y = 256
x is y # True (cached)
x = 257
y = 257
x is y # False (not cached)
15
What is the purpose of __init__.py in Python?
Medium
The __init__.py file makes a directory a Python package, allowing its modules to be imported.

Uses:
  • Marks directory as a package
  • Can contain initialization code for the package
  • Can control what gets exported via __all__
  • Can import submodules for easier access


Example structure:
mypackage/
__init__.py # Makes it a package
module1.py
module2.py

# Import
from mypackage import module1
from mypackage.module2 import some_function


Note: In Python 3.3+ namespace packages work without __init__.py
16
How does Python manage memory?
Hard
Memory Management in Python:

1. Reference Counting: Each object tracks how many references point to it. When count = 0, memory is freed.

2. Garbage Collector: Handles circular references that reference counting cannot solve.
import gc
gc.collect() # manual GC trigger


3. Memory Pools: CPython uses private heap for Python objects. Small objects use pymalloc allocator.

4. Interning: Small integers (-5 to 256) and short strings are cached and reused.

Track memory:
import sys
print(sys.getsizeof([])) # 56 bytes
print(sys.getsizeof([1,2,3])) # 88 bytes
17
What is the difference between map(), filter(), and reduce()?
Medium
map(function, iterable): Applies function to every element.
nums = [1,2,3,4]
result = list(map(lambda x: x*2, nums))
# [2, 4, 6, 8]


filter(function, iterable): Keeps elements where function returns True.
evens = list(filter(lambda x: x%2==0, nums))
# [2, 4]


reduce(function, iterable): Reduces iterable to single value (needs import).
from functools import reduce
total = reduce(lambda x,y: x+y, nums)
# 10 (1+2+3+4)
18
What is Python's with statement and context managers?
Medium
The with statement ensures resources are properly acquired and released, even if exceptions occur.

Common use — file handling:
# Without with (manual close needed)
f = open("file.txt", "r")
try:
data = f.read()
finally:
f.close()

# With with (automatic close)
with open("file.txt", "r") as f:
data = f.read()
# File auto-closed here


Custom Context Manager:
class Timer:
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
print(f"Elapsed: {time.time()-self.start:.2f}s")
19
What is the difference between mutable and immutable types in Python?
Easy
Immutable types (cannot be changed after creation):
  • int, float, complex, bool
  • str, bytes
  • tuple, frozenset

s = "hello"
s[0] = "H" # TypeError! Strings are immutable
s = "Hello" # Creates new string object


Mutable types (can be changed in-place):
  • list, dict, set
  • bytearray
  • Custom class objects

lst = [1, 2, 3]
lst[0] = 99 # OK! Lists are mutable
lst.append(4)


Key point: Immutable objects are hashable and can be dict keys.
20
Explain OOPS concepts in Python with an example.
Medium
class Animal:
# Class variable
kingdom = "Animalia"

# Constructor
def __init__(self, name, sound):
self.name = name # instance variable
self.sound = sound

# Method
def speak(self):
return f"{self.name} says {self.sound}"

# Class method
@classmethod
def get_kingdom(cls):
return cls.kingdom

# Inheritance
class Dog(Animal):
def __init__(self, name):
super().__init__(name, "Woof")

# Override
def speak(self):
return f"Dog {self.name}: Woof Woof!"

d = Dog("Buddy")
print(d.speak()) # Dog Buddy: Woof Woof!
print(d.get_kingdom()) # Animalia