PapersAdda

Top 50 Python Interview Questions for 2026

27 min read
interview-questions
Advertisement Placement

Top 50 Python Interview Questions for 2026

Last Updated: March 2026 | Level: Freshers & 1-3 Years Experience | Read Time: ~20 min

Python continues to dominate data science, web development, automation, and AI. These 50 questions cover everything from basics to advanced concepts asked in FAANG, startups, and product companies in 2026. If you're also preparing for algorithm-heavy rounds, complement this guide with our Data Structures Interview Questions 2026 and Java Interview Questions 2026.


Table of Contents

  1. Python Basics (Q1–Q15)
  2. Data Structures (Q16–Q25)
  3. OOP in Python (Q26–Q33)
  4. Libraries & Ecosystem (Q34–Q40)
  5. Advanced Python (Q41–Q50)

Python Basics

Q1. What is Python? What are its key features? Easy


Q2. What is the difference between a list and a tuple in Python? Easy

# List (mutable)
fruits = ["apple", "banana", "cherry"]
fruits[0] = "mango"      # ✅ allowed
fruits.append("grape")   # ✅ allowed

# Tuple (immutable)
coordinates = (10.5, 20.3)
# coordinates[0] = 11.0  # ❌ TypeError: 'tuple' does not support item assignment

# Tuple as dict key (possible because hashable)
locations = {(10, 20): "Home", (30, 40): "Office"}

Q3. What are Python decorators? Medium

import time
import functools

def timer(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} took {end - start:.4f}s")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)
    return "done"

slow_function()  # slow_function took 1.0012s

Q4. What is the difference between is and == in Python? Easy

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

print(a == b)   # True  (same values)
print(a is b)   # False (different objects)
print(a is c)   # True  (same object — c points to a)

# Integer interning
x = 256; y = 256
print(x is y)   # True  (cached small int)
x = 257; y = 257
print(x is y)   # False (not cached — implementation detail)

Q5. Explain Python's mutable and immutable types. Easy

# Immutable string
s = "hello"
# s[0] = 'H'  # ❌ TypeError

# What looks like modification creates a new object
s = s.upper()  # new string "HELLO", 's' now points to it

# Mutable list
lst = [1, 2, 3]
lst.append(4)   # ✅ modifies in-place
print(id(lst))  # same memory address

Q6. What are *args and **kwargs? Easy

def show(*args, **kwargs):
    print("args:", args)
    print("kwargs:", kwargs)

show(1, 2, 3, name="Alice", age=25)
# args: (1, 2, 3)
# kwargs: {'name': 'Alice', 'age': 25}

# Unpacking when calling
nums = [1, 2, 3]
info = {"name": "Bob"}
show(*nums, **info)

Q7. What is a generator in Python? How is it different from a list? Medium

# List — stores all values in memory
squares_list = [x**2 for x in range(1000000)]  # ~8MB

# Generator — computes on demand
squares_gen = (x**2 for x in range(1000000))   # ~128 bytes

def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

fib = fibonacci()
print([next(fib) for _ in range(8)])  # [0, 1, 1, 2, 3, 5, 8, 13]

Q8. What is list comprehension? Easy

# Without comprehension
squares = []
for x in range(1, 6):
    if x % 2 == 0:
        squares.append(x**2)

# With list comprehension
squares = [x**2 for x in range(1, 6) if x % 2 == 0]
# [4, 16]

# Dict comprehension
word_lengths = {word: len(word) for word in ["hello", "world", "python"]}
# {'hello': 5, 'world': 5, 'python': 6}

# Set comprehension
unique_chars = {char.lower() for char in "Hello World"}

Q9. What are Python's built-in data types? Easy


Q10. What is the GIL (Global Interpreter Lock)? Hard

# CPU-bound: use multiprocessing (not threading)
from multiprocessing import Pool

def square(n): return n * n

with Pool(4) as p:
    results = p.map(square, range(10))

# I/O-bound: asyncio works great despite GIL
import asyncio
async def fetch(url): ...  # GIL released during network wait

Q11. How does Python handle memory management? Medium


Q12. What are Python's scoping rules (LEGB)? Medium

x = "global"

def outer():
    x = "enclosing"
    
    def inner():
        x = "local"
        print(x)     # local
    
    inner()
    print(x)         # enclosing

outer()
print(x)             # global

# nonlocal example
def counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

c = counter()
print(c(), c(), c())  # 1 2 3

Q13. What is the difference between deepcopy and copy? Medium

import copy

original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)

original[0][0] = 99

print(shallow[0][0])  # 99  — shared inner list!
print(deep[0][0])     # 1   — completely independent

Q14. What is __init__ vs __new__ in Python? Hard

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

s1 = Singleton()
s2 = Singleton()
print(s1 is s2)  # True — same instance

Q15. What are Python's comparison operators and how does chaining work? Easy

x = 5
print(1 < x < 10)    # True (chained: 1<5 and 5<10)
print(1 < x < 4)     # False

# Membership
fruits = ["apple", "banana"]
print("apple" in fruits)     # True
print("mango" not in fruits) # True

Data Structures

Q16. How does a Python dictionary work internally? Hard

# Dict operations — all O(1) average
d = {"name": "Alice", "age": 25}
d["city"] = "Mumbai"    # O(1) insert
val = d["name"]         # O(1) lookup
del d["age"]            # O(1) delete

# dict comprehension
squares = {i: i**2 for i in range(5)}  # {0:0, 1:1, 2:4, 3:9, 4:16}

# Merging dicts (Python 3.9+)
dict1 = {"a": 1}
dict2 = {"b": 2}
merged = dict1 | dict2   # {"a": 1, "b": 2}

Q17. What is a set in Python? When would you use it? Easy

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

# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a & b)   # intersection: {3, 4}
print(a | b)   # union: {1, 2, 3, 4, 5, 6}
print(a - b)   # difference: {1, 2}
print(a ^ b)   # symmetric difference: {1, 2, 5, 6}

Q18. How do you reverse a string/list in Python? Easy

s = "Hello, Python!"
print(s[::-1])       # "!nohtyP ,olleH"

lst = [1, 2, 3, 4, 5]
print(lst[::-1])     # [5, 4, 3, 2, 1] — new list
lst.reverse()        # in-place
print(list(reversed(lst)))  # iterator-based

Q19. How do you sort a list of dictionaries by a key? Medium

students = [
    {"name": "Alice", "grade": 88},
    {"name": "Bob",   "grade": 95},
    {"name": "Charlie", "grade": 72}
]

# Sort by grade (ascending)
sorted_students = sorted(students, key=lambda s: s["grade"])

# Sort by grade (descending), then name (ascending)
sorted_students = sorted(students, key=lambda s: (-s["grade"], s["name"]))

print(sorted_students[0])  # {'name': 'Bob', 'grade': 95}

Q20. What is a deque and when would you use it? Medium

from collections import deque

dq = deque([1, 2, 3])
dq.appendleft(0)     # O(1): [0, 1, 2, 3]
dq.append(4)         # O(1): [0, 1, 2, 3, 4]
dq.popleft()         # O(1): returns 0
dq.pop()             # O(1): returns 4

# Sliding window maximum using deque
def sliding_max(arr, k):
    dq = deque()
    result = []
    for i, num in enumerate(arr):
        while dq and arr[dq[-1]] < num: dq.pop()
        dq.append(i)
        if dq[0] == i - k: dq.popleft()
        if i >= k - 1: result.append(arr[dq[0]])
    return result

Q21. How do you find duplicates in a list? Easy

from collections import Counter

lst = [1, 2, 3, 2, 4, 3, 5]

# Using Counter
counts = Counter(lst)  # Counter({2: 2, 3: 2, 1: 1, 4: 1, 5: 1})
duplicates = [x for x, count in counts.items() if count > 1]
print(duplicates)   # [2, 3]

# Using set
seen, dupes = set(), set()
for x in lst:
    if x in seen: dupes.add(x)
    seen.add(x)

Q22. What is defaultdict? Medium

from collections import defaultdict

# Without defaultdict
word_count = {}
for word in ["apple", "banana", "apple"]:
    if word not in word_count:
        word_count[word] = 0
    word_count[word] += 1

# With defaultdict
word_count = defaultdict(int)
for word in ["apple", "banana", "apple"]:
    word_count[word] += 1  # auto-initializes to 0

# Group by first letter
from_letter = defaultdict(list)
for word in ["apple", "avocado", "banana"]:
    from_letter[word[0]].append(word)
# {'a': ['apple', 'avocado'], 'b': ['banana']}

Q23. How do you flatten a nested list? Medium

import itertools

# One level deep
nested = [[1, 2], [3, 4], [5, 6]]
flat = list(itertools.chain.from_iterable(nested))  # [1, 2, 3, 4, 5, 6]

# List comprehension
flat = [x for sublist in nested for x in sublist]

# Recursive for arbitrary depth
def flatten(lst):
    result = []
    for item in lst:
        if isinstance(item, list):
            result.extend(flatten(item))
        else:
            result.append(item)
    return result

deep = [[1, [2, 3]], [4, [5, [6]]]]
print(flatten(deep))  # [1, 2, 3, 4, 5, 6]

Q24. What is the time complexity of common Python operations? Medium

Operationlistdict/set
Access by indexO(1)N/A
Search (in)O(n)O(1) avg
Insert at endO(1) amortizedO(1) avg
Insert at beginningO(n)N/A
DeleteO(n)O(1) avg
# Demonstrate O(n) list search vs O(1) set search
import time

data = list(range(1_000_000))
data_set = set(data)
target = 999_999

# List: O(n)
start = time.time(); target in data; print(f"List: {time.time()-start:.5f}s")

# Set: O(1)
start = time.time(); target in data_set; print(f"Set: {time.time()-start:.5f}s")

Q25. How do you merge two dictionaries in Python? Easy

d1 = {"a": 1, "b": 2}
d2 = {"b": 99, "c": 3}

# Method 1: Unpacking (Python 3.5+)
merged = {**d1, **d2}        # {"a": 1, "b": 99, "c": 3}

# Method 2: | operator (Python 3.9+)
merged = d1 | d2             # {"a": 1, "b": 99, "c": 3}

# Method 3: update (modifies d1 in-place)
d1.update(d2)                # d1 becomes {"a": 1, "b": 99, "c": 3}

OOP in Python

Q26. What are dunder (magic) methods in Python? Medium

class Vector:
    def __init__(self, x, y):
        self.x, self.y = x, y
    
    def __repr__(self):
        return f"Vector({self.x}, {self.y})"
    
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)
    
    def __len__(self):
        return int((self.x**2 + self.y**2) ** 0.5)
    
    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1 + v2)    # Vector(4, 6)
print(len(v2))    # 5

Q27. What is inheritance in Python? How do you call a parent method? Easy

class Animal:
    def __init__(self, name):
        self.name = name
    
    def speak(self):
        raise NotImplementedError

class Dog(Animal):
    def __init__(self, name, breed):
        super().__init__(name)    # call parent __init__
        self.breed = breed
    
    def speak(self):
        return f"{self.name} says Woof!"

class GuideDog(Dog):
    def speak(self):
        return super().speak() + " (Guide Dog)"

gd = GuideDog("Rex", "Labrador")
print(gd.speak())  # Rex says Woof! (Guide Dog)

Q28. What is multiple inheritance and the MRO? Hard

class A:
    def method(self): print("A")

class B(A):
    def method(self): print("B")

class C(A):
    def method(self): print("C")

class D(B, C):   # MRO: D → B → C → A
    pass

d = D()
d.method()        # "B" — follows MRO
print(D.__mro__)  # (<class 'D'>, <class 'B'>, <class 'C'>, <class 'A'>, ...)

Q29. What are classmethods and staticmethods? Medium

class Date:
    def __init__(self, year, month, day):
        self.year, self.month, self.day = year, month, day
    
    @classmethod
    def from_string(cls, date_str):        # factory method
        year, month, day = map(int, date_str.split("-"))
        return cls(year, month, day)       # creates instance via cls
    
    @staticmethod
    def is_valid(year, month, day):        # utility — no self/cls
        return 1 <= month <= 12 and 1 <= day <= 31

d = Date.from_string("2026-03-08")
print(Date.is_valid(2026, 3, 8))   # True

Q30. What is a property in Python? Medium

class Temperature:
    def __init__(self, celsius=0):
        self._celsius = celsius
    
    @property
    def celsius(self):
        return self._celsius
    
    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("Temperature below absolute zero!")
        self._celsius = value
    
    @property
    def fahrenheit(self):
        return self._celsius * 9/5 + 32    # computed property

t = Temperature(25)
print(t.fahrenheit)    # 77.0
t.celsius = -274       # raises ValueError

Q31. What is duck typing in Python? Medium

class Duck:
    def quack(self): print("Quack!")
    def walk(self): print("Waddle")

class Person:
    def quack(self): print("I'm quacking like a duck!")
    def walk(self): print("Walking like a duck")

def make_it_quack(duck_like):
    duck_like.quack()   # works for any object with quack()

make_it_quack(Duck())    # Quack!
make_it_quack(Person())  # I'm quacking like a duck!

Q32. What are abstract classes in Python? Medium

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self) -> float:
        pass
    
    @abstractmethod
    def perimeter(self) -> float:
        pass
    
    def describe(self):    # concrete shared method
        print(f"Area: {self.area():.2f}, Perimeter: {self.perimeter():.2f}")

class Circle(Shape):
    def __init__(self, r): self.r = r
    def area(self): return 3.14159 * self.r ** 2
    def perimeter(self): return 2 * 3.14159 * self.r

# Shape()    # ❌ TypeError: Can't instantiate abstract class
Circle(5).describe()   # Area: 78.54, Perimeter: 31.42

Q33. What is __slots__ in Python? Hard

class Point:
    __slots__ = ['x', 'y']   # only x and y allowed
    
    def __init__(self, x, y):
        self.x, self.y = x, y

p = Point(1, 2)
# p.z = 3   # ❌ AttributeError: 'Point' has no attribute 'z'

# Memory comparison: regular class uses ~232 bytes, slots class ~56 bytes

Libraries & Ecosystem

Q34. What is NumPy and why is it fast? Medium

import numpy as np

# Vectorized operations (no Python loops)
arr = np.array([1, 2, 3, 4, 5])
print(arr * 2)          # [2, 4, 6, 8, 10]
print(arr ** 2)         # [1, 4, 9, 16, 25]
print(np.mean(arr))     # 3.0

# Broadcasting
matrix = np.zeros((3, 3))
matrix += 5             # add 5 to every element

# Performance: NumPy vs Python list
import time
lst = list(range(1_000_000))
arr = np.array(lst)

start = time.time(); [x*2 for x in lst]; print(f"List: {time.time()-start:.3f}s")
start = time.time(); arr * 2;            print(f"NumPy: {time.time()-start:.3f}s")

Q35. What is Pandas and how do you handle missing data? Medium

import pandas as pd
import numpy as np

df = pd.DataFrame({
    "name": ["Alice", "Bob", None, "Diana"],
    "age": [25, np.nan, 30, 28],
    "score": [85, 90, np.nan, 78]
})

print(df.isnull().sum())         # count missing per column
df["age"].fillna(df["age"].mean(), inplace=True)  # fill with mean
df.dropna(subset=["name"], inplace=True)          # drop rows where name is null
df["score"] = df["score"].interpolate()           # interpolate missing scores

Q36. What is Flask vs Django? Easy


Q37. What is asyncio in Python? Hard

import asyncio
import aiohttp

async def fetch(session, url):
    async with session.get(url) as response:
        return await response.text()

async def main():
    urls = ["https://api.github.com", "https://httpbin.org/get"]
    
    async with aiohttp.ClientSession() as session:
        tasks = [fetch(session, url) for url in urls]
        results = await asyncio.gather(*tasks)   # concurrent!
    
    return results

asyncio.run(main())

Q38. How do you read and write files in Python? Easy

# Writing
with open("data.txt", "w") as f:
    f.write("Hello, Python!\n")
    f.writelines(["Line 2\n", "Line 3\n"])

# Reading
with open("data.txt", "r") as f:
    content = f.read()          # entire file as string
    # lines = f.readlines()     # list of lines
    # for line in f:            # iterate line by line (memory efficient)

# JSON
import json
data = {"name": "Alice", "age": 25}
with open("data.json", "w") as f:
    json.dump(data, f, indent=2)

with open("data.json") as f:
    loaded = json.load(f)

Q39. What is itertools and give two useful examples? Medium

import itertools

# combinations and permutations
items = ['A', 'B', 'C']
print(list(itertools.combinations(items, 2)))
# [('A','B'), ('A','C'), ('B','C')]

print(list(itertools.permutations(items, 2)))
# [('A','B'), ('A','C'), ('B','A'), ('B','C'), ('C','A'), ('C','B')]

# chain — iterate multiple iterables as one
for item in itertools.chain([1,2], [3,4], [5,6]):
    print(item, end=" ")  # 1 2 3 4 5 6

# groupby — group consecutive elements
data = [("fruit","apple"), ("fruit","banana"), ("veg","carrot")]
for key, group in itertools.groupby(data, key=lambda x: x[0]):
    print(key, list(group))

Q40. What is pytest and how do you write a basic test? Medium

# calculator.py
def add(a, b): return a + b
def divide(a, b):
    if b == 0: raise ValueError("Cannot divide by zero")
    return a / b

# test_calculator.py
import pytest
from calculator import add, divide

def test_add():
    assert add(2, 3) == 5
    assert add(-1, 1) == 0

def test_divide():
    assert divide(10, 2) == 5.0

def test_divide_by_zero():
    with pytest.raises(ValueError, match="Cannot divide by zero"):
        divide(10, 0)

@pytest.mark.parametrize("a,b,expected", [(1,2,3), (0,0,0), (-1,-1,-2)])
def test_add_parametrized(a, b, expected):
    assert add(a, b) == expected

Advanced Python

Q41. What is a closure in Python? Medium

def make_multiplier(factor):
    def multiply(n):
        return n * factor    # 'factor' is closed over
    return multiply          # returns function, not result

triple = make_multiplier(3)
quintuple = make_multiplier(5)

print(triple(10))      # 30
print(quintuple(10))   # 50
print(triple.__closure__[0].cell_contents)  # 3

Q42. What is monkey patching? Hard

class MyClass:
    def say_hello(self):
        print("Hello")

def patched_hello(self):
    print("Patched Hello!")

MyClass.say_hello = patched_hello   # monkey patch

obj = MyClass()
obj.say_hello()   # "Patched Hello!"

# Common in testing with unittest.mock
from unittest.mock import patch

with patch("os.path.exists", return_value=True):
    import os
    print(os.path.exists("fake_path"))  # True

Q43. What are context managers? How do you create one? Medium

from contextlib import contextmanager
import time

@contextmanager
def timer(name):
    start = time.time()
    try:
        yield               # execution passes to with block
    finally:
        elapsed = time.time() - start
        print(f"{name}: {elapsed:.4f}s")

with timer("heavy_computation"):
    result = sum(range(1_000_000))

# Class-based
class DatabaseConnection:
    def __enter__(self):
        print("Opening connection")
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Closing connection")
        return False  # don't suppress exceptions

Q44. What is metaclass in Python? Hard

class SingletonMeta(type):
    _instances = {}
    
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]

class DatabasePool(metaclass=SingletonMeta):
    def __init__(self):
        self.connections = []

db1 = DatabasePool()
db2 = DatabasePool()
print(db1 is db2)   # True — same instance

Q45. What is the difference between @staticmethod, @classmethod, and regular methods? Medium


Q46. What are Python type hints and why use them? Medium

from typing import Optional, Union, List

def process_data(
    items: list[int],
    factor: float = 1.0,
    label: Optional[str] = None
) -> dict[str, Union[int, float]]:
    total = sum(item * factor for item in items)
    return {"total": total, "count": len(items)}

# Python 3.10+ syntax
def greet(name: str | None = None) -> str:
    return f"Hello, {name or 'World'}!"

Q47. What is pickling in Python? Medium

import pickle

data = {"model": "sklearn_model", "params": [1, 2, 3], "scores": [0.95, 0.92]}

# Serialize (pickle)
with open("model.pkl", "wb") as f:
    pickle.dump(data, f)

# Deserialize (unpickle)
with open("model.pkl", "rb") as f:
    loaded = pickle.load(f)

# In-memory
serialized = pickle.dumps(data)
restored = pickle.loads(serialized)

Q48. What is functools.lru_cache and when would you use it? Medium

from functools import lru_cache
import time

@lru_cache(maxsize=None)  # unbounded cache
def fibonacci(n):
    if n < 2: return n
    return fibonacci(n-1) + fibonacci(n-2)

start = time.time()
print(fibonacci(100))   # 354224848179261915075
print(f"Time: {time.time()-start:.6f}s")   # instant with caching

# View cache stats
print(fibonacci.cache_info())
# CacheInfo(hits=98, misses=101, maxsize=None, currsize=101)

Q49. What is the difference between map(), filter(), and reduce()? Medium

from functools import reduce

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# map — transform each element
squared = list(map(lambda x: x**2, numbers))
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

# filter — keep matching elements
evens = list(filter(lambda x: x % 2 == 0, numbers))
# [2, 4, 6, 8, 10]

# reduce — cumulative operation
product = reduce(lambda a, b: a * b, numbers)
# 3628800 (10!)

# Modern Pythonic style (often preferred)
squared = [x**2 for x in numbers]
evens = [x for x in numbers if x % 2 == 0]

Q50. What are some best practices for writing Pythonic code? Medium

# EAFP (Pythonic) vs LBYL (non-Pythonic)
# LBYL
if key in dictionary:
    value = dictionary[key]

# EAFP (Pythonic)
try:
    value = dictionary[key]
except KeyError:
    value = default

# enumerate instead of range(len())
names = ["Alice", "Bob", "Charlie"]
for i, name in enumerate(names):    # ✅ Pythonic
    print(f"{i}: {name}")

# zip for parallel iteration
ages = [25, 30, 28]
for name, age in zip(names, ages):  # ✅ Pythonic
    print(f"{name}: {age}")

# f-strings (Python 3.6+)
name, score = "Alice", 95.5
print(f"{name} scored {score:.1f}%")  # ✅ Pythonic

Quick Reference Table

ConceptKey Points
GILCPython limitation; use multiprocessing for CPU-bound
List vs TupleMutable vs Immutable; tuple = hashable
GeneratorsLazy evaluation, memory efficient
DecoratorsFunctions that wrap functions
LEGB ScopeLocal → Enclosing → Global → Built-in
Deep vs Shallowdeepcopy = fully independent clone


© 2026 PlacementAdda.com | Stay Pythonic, Stay Hired

Advertisement Placement

Explore this topic cluster

More resources in interview-questions

Use the category hub to browse similar questions, exam patterns, salary guides, and preparation resources related to this topic.

More in interview-questions

More from PapersAdda

Share this article: