Python Interview Questions and Answers (75+ Advanced Questions)

Python Interview Questions and Answers

This guide is designed for Cloud Engineer, Data Engineer, AI Engineer, Solution Architect, DevOps Engineer, Software Engineer, and Technical Architect interviews.


1. What is Python?

Answer

Python is a high-level, interpreted, object-oriented, dynamically typed programming language developed by Guido van Rossum.

Features:

  • Easy to learn
  • Platform independent
  • Open source
  • Large standard library
  • Supports OOP and Functional Programming
  • Automatic memory management

Example:

print("Hello World")

2. What are the advantages of Python?

Answer

Advantages:

  1. Easy Syntax
  2. Rapid Development
  3. Huge Community Support
  4. Rich Libraries
  5. Cross-platform
  6. Supports AI/ML
  7. Excellent Cloud Integration
  8. Automation Friendly

3. Is Python Compiled or Interpreted?

Answer

Python is both.

Process:

Python Code

Bytecode (.pyc)

Python Virtual Machine (PVM)

Execution

Python first compiles source code into bytecode and then interprets it.


4. What is PEP 8?

Answer

PEP = Python Enhancement Proposal

PEP 8 is Python’s coding style guide.

Examples:

# Good

user_name = "John"

# Bad

UserName="John"

Guidelines:

  • 4 spaces indentation
  • Max line length 79
  • Use snake_case for variables
  • Use CamelCase for classes

5. Difference between List and Tuple

FeatureListTuple
MutableYesNo
Syntax[]()
PerformanceSlowerFaster
HashableNoYes

Example:

mylist = [1,2,3]
mytuple = (1,2,3)

6. Difference between List and Set

List

[1,1,2,3]

Allows duplicates.

Set

{1,2,3}

Removes duplicates automatically.


7. Difference between append() and extend()

append()

a=[1,2]
a.append([3,4])

print(a)

Output:

[1,2,[3,4]]

extend()

a=[1,2]
a.extend([3,4])

Output:

[1,2,3,4]

8. What is Dictionary?

Answer

Dictionary stores key-value pairs.

employee={
"name":"John",
"age":30
}

Access:

employee["name"]

9. Difference between == and is

==

Compares values.

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

a==b

True

is

Compares memory location.

a is b

False


10. What are Python Data Types?

Answer

Built-in types:

int
float
str
bool
list
tuple
set
dict
NoneType

11. What is None?

Answer

Represents absence of value.

x=None

Type:

type(None)

Output:

<class 'NoneType'>

12. What is Mutable and Immutable?

Mutable

Can change after creation.

list
dict
set

Immutable

Cannot change.

int
float
str
tuple

13. What is List Comprehension?

Answer

Compact way to create lists.

squares = [x*x for x in range(5)]

Output:

[0,1,4,9,16]

14. What is Lambda Function?

Answer

Anonymous function.

square = lambda x: x*x

print(square(5))

Output:

25

15. What are map(), filter(), reduce()?

map()

nums=[1,2,3]

list(map(lambda x:x*2, nums))

filter()

list(filter(lambda x:x>2, nums))

reduce()

from functools import reduce

reduce(lambda x,y:x+y, nums)

16. What is *args?

Answer

Accepts variable positional arguments.

def add(*args):
return sum(args)

17. What is **kwargs?

Answer

Accepts variable keyword arguments.

def show(**kwargs):
print(kwargs)

18. What is a Generator?

Answer

Produces values lazily using yield.

def numbers():
yield 1
yield 2

Benefits:

  • Memory efficient
  • Faster for large datasets

19. Generator vs Iterator

GeneratorIterator
Uses yieldUses next
EasierComplex
Auto-createdManual

20. What is Iterator?

Answer

Object that implements:

__iter__()
__next__()

Example:

nums=iter([1,2,3])

next(nums)

21. What is Decorator?

Answer

Function modifying another function.

def log(func):
def wrapper():
print("Start")
func()
return wrapper

22. Why use Decorators?

  • Logging
  • Authentication
  • Authorization
  • Monitoring
  • Caching

Common in:

  • Flask
  • FastAPI
  • Django

23. What is Closure?

Answer

Inner function remembers outer variables.

def outer(x):
def inner():
return x
return inner

24. What is Recursion?

Answer

Function calling itself.

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

25. What is Exception Handling?

Answer

Handling runtime errors.

try:
x=10/0
except ZeroDivisionError:
print("Error")

26. Difference between Exception and Error

Error

System level issue.

Exception

Recoverable issue.


27. Explain try-except-else-finally

try:
pass
except:
pass
else:
pass
finally:
pass

Finally always executes.


28. What is Custom Exception?

class AgeError(Exception):
pass

29. What is OOP?

Object-Oriented Programming based on:

  1. Encapsulation
  2. Inheritance
  3. Polymorphism
  4. Abstraction

30. What is Class?

class Employee:
pass

Blueprint of object.


31. What is Object?

emp=Employee()

Instance of class.


32. What is Constructor?

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

33. What is Encapsulation?

Hiding implementation details.

class Bank:
def __init__(self):
self.__balance=1000

34. What is Inheritance?

class Animal:
pass

class Dog(Animal):
pass

35. Types of Inheritance

  • Single
  • Multiple
  • Multilevel
  • Hierarchical
  • Hybrid

36. What is Polymorphism?

Same interface, different behavior.

class Dog:
def speak(self):
return "Bark"

class Cat:
def speak(self):
return "Meow"

37. What is Method Overriding?

class Parent:
def show(self):
print("Parent")

class Child(Parent):
def show(self):
print("Child")

38. What is Abstraction?

Hide complexity.

from abc import ABC

39. What are Magic Methods?

Examples:

__init__
__str__
__len__
__repr__

40. Difference between str and repr

str

Human readable.

repr

Developer/debugging representation.


41. What is GIL?

Global Interpreter Lock

Allows only one thread to execute Python bytecode at a time.

Important Interview Point:

  • Multi-threading good for I/O
  • Multi-processing good for CPU

42. What is Multithreading?

from threading import Thread

Used for:

  • API Calls
  • File operations
  • Database operations

43. What is Multiprocessing?

from multiprocessing import Process

Uses multiple CPUs.


44. Thread vs Process

ThreadProcess
Shared memorySeparate memory
LightweightHeavy
FasterSlower

45. What is Context Manager?

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

Automatically handles cleanup.


46. What is enter and exit?

Used in custom context managers.

class Demo:
def __enter__(self):
pass

def __exit__(self,*args):
pass

47. What is Deep Copy vs Shallow Copy?

Shallow

copy.copy()

Copies references.

Deep

copy.deepcopy()

Copies complete objects.


48. What is Python Memory Management?

Managed by:

  • Private Heap
  • Reference Counting
  • Garbage Collector

49. What is Garbage Collection?

Automatic cleanup of unused objects.

import gc

50. What is Reference Counting?

Python tracks references.

import sys

sys.getrefcount(obj)

51. What is Virtual Environment?

Creates isolated Python environment.

python -m venv myenv

52. What is pip?

Package manager.

pip install pandas

53. What is Python Packaging?

Tools:

  • setuptools
  • wheel
  • pip

54. What is Module?

Single Python file.

math.py

55. What is Package?

Collection of modules.

mypackage/
__init__.py

56. What is Namespace?

Mapping between names and objects.

Types:

  • Local
  • Global
  • Built-in
  • Enclosing

57. What is LEGB Rule?

Search order:

Local
Enclosing
Global
Built-in

58. What is Monkey Patching?

Runtime modification.

module.func = new_func

59. What is Duck Typing?

“If it walks like a duck and quacks like a duck…”

Focus on behavior not type.


60. What are Python Collections?

Counter
defaultdict
namedtuple
deque

From:

collections

61. What is defaultdict?

from collections import defaultdict

d=defaultdict(int)

62. What is deque?

Double-ended queue.

from collections import deque

Fast insertions.


63. What is NamedTuple?

from collections import namedtuple

Tuple with named fields.


64. What is Asyncio?

Asynchronous programming framework.

async def main():
pass

65. async vs await

async def fetch():
await api_call()

async → coroutine definition

await → waits non-blocking


66. What is Coroutine?

Function that can pause and resume.

async def task():
pass

67. What is FastAPI?

FastAPI is a modern high-performance Python API framework.

Features:

  • Async support
  • Swagger UI
  • Type hints
  • High performance

68. What is Flask?

Flask is a lightweight Python web framework.


69. Flask vs FastAPI

FlaskFastAPI
SyncAsync
SlowerFaster
Manual docsAuto docs

70. What is Django?

Django is a full-stack web framework.

Features:

  • ORM
  • Authentication
  • Admin Portal
  • Security

71. What are Python Type Hints?

def add(a:int,b:int)->int:
return a+b

Improves readability.


72. What is Dataclass?

from dataclasses import dataclass

@dataclass
class Employee:
name:str

Auto-generates boilerplate code.


73. What is Unit Testing?

import unittest

Tests individual components.


74. What is PyTest?

pytest is the most popular Python testing framework.

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

75. What is Python Used For in AI/Data Engineering?

AI/ML

  • TensorFlow
  • PyTorch
  • LangChain
  • Bedrock Integrations

Data Engineering

  • Pandas
  • PySpark
  • Airflow
  • AWS Glue

Cloud

  • Lambda
  • EKS
  • ECS
  • Automation

Bonus Advanced Interview Questions

76. What is Metaclass?

Class that creates classes.

class Meta(type):
pass

77. What is Method Resolution Order (MRO)?

Class.__mro__

Determines inheritance lookup order.


78. What is Descriptor?

Controls attribute access.

Methods:

__get__
__set__
__delete__

79. What is Weak Reference?

Reference that doesn’t increase reference count.

import weakref

80. What is Serialization?

Convert object into storable format.

import json
import pickle

Top 10 Python Questions Asked in AWS/AI Interviews

  1. Explain GIL and how it impacts performance.
  2. Difference between Threading and Multiprocessing.
  3. Explain Generators and Yield.
  4. Explain Decorators with examples.
  5. Explain Memory Management.
  6. Difference between Deep Copy and Shallow Copy.
  7. Explain Async/Await.
  8. What are Context Managers?
  9. Explain OOP concepts with examples.
  10. Explain Python’s LEGB rule and closures.

These 80 questions cover roughly 90–95% of Python interview topics commonly asked for Cloud Engineer, Data Engineer, AI Engineer, DevOps Engineer, AWS Architect, and Technical Architect roles.

Here is a comprehensive list of 75+ Python interview questions (highest priority), covering basic, intermediate, advanced, OOP, data structures, functional programming, concurrency, debugging, and coding scenarios. Each answer is detailed and practical.


🔹 Part 1: Core Python Basics (15+ questions)

1. What is Python? What are its key features?

Answer:
Python is a high-level, interpreted, dynamically typed, object-oriented programming language.
Key features:

  • Easy to learn and read
  • Interpreted (no compilation step)
  • Dynamically typed
  • Extensive standard library
  • Platform independent
  • Garbage collected
  • Supports multiple paradigms (OOP, functional, procedural)

2. What are the differences between a list and a tuple?

FeatureListTuple
MutabilityMutableImmutable
PerformanceSlowerFaster
MemoryMoreLess
Use caseDynamic dataFixed data / dict keys

Example:

python

my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
my_list[0] = 99   # OK
my_tuple[0] = 99  # TypeError

3. What is the difference between deepcopy and shallow copy?

  • Shallow copy: Creates new object but inserts references to original nested objects.
  • Deep copy: Recursively copies all nested objects.

python

import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)   # nested lists are shared
deep = copy.deepcopy(original)  # fully independent

4. How does Python manage memory?

  • Uses private heap to store objects.
  • Reference counting + garbage collector (for cyclic references).
  • gc module for manual control.

5. What is __name__ == "__main__"?

It ensures code runs only when script is executed directly, not when imported as module.


6. Explain mutable vs immutable types with examples.

  • Immutable: int, float, str, tuple, frozenset
  • Mutable: list, dict, set, bytearray

python

s = "hello"
s[0] = "H"   # ❌ TypeError

7. What is pass in Python?

A null operation — used as a placeholder for syntactically required blocks.


8. Difference between range and xrange (Python 2)?

In Python 3, range = xrange (lazy evaluation). range returns iterator, not list.


9. What are Python decorators?

Functions that modify behavior of another function.

python

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

@my_decorator
def say_hello():
    print("Hello")

10. What are lambda functions?

Anonymous single-expression functions.

python

square = lambda x: x**2

11. Explain *args and **kwargs.

  • *args: variable positional arguments → tuple
  • **kwargs: variable keyword arguments → dict

12. What are list comprehensions?

Concise way to create lists.

python

squares = [x**2 for x in range(10)]

13. Difference between is and ==?

  • == checks value equality
  • is checks identity (memory address)

14. How to handle exceptions in Python?

try-except-else-finally blocks.

python

try:
    x = 1 / 0
except ZeroDivisionError:
    print("Error")
else:
    print("No error")
finally:
    print("Always runs")

15. What are built-in data types in Python?

  • Numeric: int, float, complex
  • Text: str
  • Sequence: list, tuple, range
  • Mapping: dict
  • Set: set, frozenset
  • Boolean: bool
  • Binary: bytes, bytearray, memoryview
  • None

🔹 Part 2: Intermediate Python (15+ questions)

16. What are generators and yield?

Generators produce items lazily, one at a time.

python

def count_down(n):
    while n > 0:
        yield n
        n -= 1

17. Explain the GIL (Global Interpreter Lock).

GIL allows only one thread to execute Python bytecode at a time, simplifying memory management but limiting true parallelism for CPU-bound tasks.


18. Difference between multithreading and multiprocessing.

MultithreadingMultiprocessing
GIL impactBlocked for CPU tasksNo GIL (separate memory)
Best forI/O tasksCPU tasks

19. What is a decorator factory?

Decorator that accepts arguments.

python

def repeat(n):
    def decorator(func):
        def wrapper(*args):
            for _ in range(n):
                func(*args)
        return wrapper
    return decorator

20. Explain @staticmethod and @classmethod.

  • @staticmethod: no self/cls → like regular function but inside class
  • @classmethod: receives cls → can modify class state

21. What is method resolution order (MRO)?

Order Python searches for methods in inheritance hierarchy. Access via ClassName.__mro__.


22. What is __slots__?

Reduces memory by preventing dynamic attribute creation.

python

class Point:
    __slots__ = ('x', 'y')

23. How to reverse a string in Python?

python

s[::-1]
''.join(reversed(s))

24. Difference between removepop, and del on lists.

  • remove(value) – removes first match
  • pop(index) – removes and returns item
  • del list[index] – deletes without return

25. What is pickling and unpickling?

Serialization using pickle module.

python

import pickle
data = {"a": 1}
with open("file.pkl", "wb") as f:
    pickle.dump(data, f)

26. Explain with statement (context manager).

Ensures resource cleanup (e.g., file close, lock release).

python

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

27. What is sys.argv?

List of command-line arguments passed to Python script.


28. How to check memory usage of an object?

python

import sys
sys.getsizeof(obj)

29. What is functools.partial?

Pre-fills some arguments of a function.

python

from functools import partial
def power(base, exp): return base ** exp
square = partial(power, exp=2)

30. Difference between mapfilter, and reduce.

  • map(func, iterable) – apply function
  • filter(func, iterable) – keep True elements
  • reduce(func, iterable) – cumulative application (in functools)

🔹 Part 3: OOP in Python (10+ questions)

31. Explain inheritance and polymorphism with example.

python

class Animal:
    def speak(self): pass

class Dog(Animal):
    def speak(self): return "Woof"

32. What is method overriding?

Subclass redefines a method from parent.


33. What is super()?

Calls parent class method.


34. Difference between public, protected, and private in Python.

  • Public: var
  • Protected: _var (convention)
  • Private: __var (name mangling)

35. What are abstract base classes (ABC)?

Classes that cannot be instantiated and require subclasses to implement methods.

python

from abc import ABC, abstractmethod
class Shape(ABC):
    @abstractmethod
    def area(self): pass

36. What is composition vs inheritance?

  • Inheritance: “is-a” relationship (e.g., Dog is Animal)
  • Composition: “has-a” relationship (e.g., Car has Engine)

37. Can you have multiple constructors in Python?

No, but you can use @classmethod to create alternative constructors.

python

class Person:
    def __init__(self, name): self.name = name
    @classmethod
    def from_birthyear(cls, name, year): ...

38. What is __new__ vs __init__?

  • __new__: creates instance (constructor)
  • __init__: initializes instance

39. Explain diamond problem in multiple inheritance.

Resolved via MRO (C3 linearization).


40. What are magic/dunder methods?

Examples: __str____repr____len____call____add__.


🔹 Part 4: Data Structures & Algorithms (10+ questions)

41. How to find duplicates in a list?

python

seen = set()
dupes = set()
for i in lst:
    if i in seen: dupes.add(i)
    else: seen.add(i)

42. Reverse a linked list in-place.

python

def reverse(head):
    prev = None
    while head:
        nxt = head.next
        head.next = prev
        prev = head
        head = nxt
    return prev

43. Check if string is palindrome ignoring case.

python

s = "A man a plan a canal panama"
cleaned = ''.join(c.lower() for c in s if c.isalnum())
print(cleaned == cleaned[::-1])

44. Find the most frequent element in list.

python

from collections import Counter
most_common = Counter(lst).most_common(1)[0][0]

45. Merge two sorted lists.

python

def merge(a, b):
    i = j = 0
    res = []
    while i < len(a) and j < len(b):
        if a[i] < b[j]:
            res.append(a[i]); i+=1
        else:
            res.append(b[j]); j+=1
    res.extend(a[i:]); res.extend(b[j:])
    return res

46. Implement a stack using list.

python

stack = []
stack.append(1)   # push
stack.pop()       # pop

47. Implement queue using collections.deque.

python

from collections import deque
q = deque()
q.append(1)  # enqueue
q.popleft()  # dequeue

48. Find first non-repeating character in string.

python

from collections import Counter
count = Counter(s)
for ch in s:
    if count[ch] == 1: return ch

49. Two-sum problem.

python

def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        diff = target - n
        if diff in seen: return [seen[diff], i]
        seen[n] = i

50. Check if two strings are anagrams.

python

from collections import Counter
return Counter(s1) == Counter(s2)

🔹 Part 5: Functional & Advanced Python (10+ questions)

51. What is itertools used for?

Efficient looping tools: productpermutationscombinationscyclechain.


52. Explain closures.

Inner function remembering outer function’s variables.

python

def outer(x):
    def inner(y):
        return x + y
    return inner
add5 = outer(5)
add5(3)  # 8

53. What is functools.lru_cache?

Memoization decorator.

python

@lru_cache(maxsize=128)
def fib(n):
    return n if n < 2 else fib(n-1) + fib(n-2)

54. What are decorators with arguments?

python

@repeat(3)
def greet(): print("Hi")

55. What is typing module?

For type hints (not enforced at runtime).

python

def greet(name: str) -> str:
    return f"Hello {name}"

56. Explain asyncio vs threading.

  • asyncio: single-threaded, event-loop based (high concurrency for I/O)
  • threading: OS threads (better for blocking I/O)

57. How to run async functions?

python

import asyncio
async def main(): print("Hello")
asyncio.run(main())

58. What is global and nonlocal?

  • global: modify module-level variable
  • nonlocal: modify enclosing function variable

59. Explain eval vs exec.

  • eval: evaluates single expression
  • exec: executes dynamic code (statements)

60. What are weak references (weakref)?

Prevent objects from being kept alive just by reference.


🔹 Part 6: Common Coding Questions (10+ questions)

61. Flatten a nested list.

python

def flatten(lst):
    result = []
    for i in lst:
        if isinstance(i, list):
            result.extend(flatten(i))
        else:
            result.append(i)
    return result

62. Check balanced parentheses.

python

def is_balanced(s):
    stack = []
    pairs = {')': '(', '}': '{', ']': '['}
    for ch in s:
        if ch in pairs.values():
            stack.append(ch)
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
    return not stack

63. Remove duplicates from list while preserving order.

python

seen = set()
result = []
for item in lst:
    if item not in seen:
        seen.add(item)
        result.append(item)

64. Find intersection of two lists.

python

set(list1) & set(list2)

65. Count vowels in a string.

python

sum(1 for ch in s.lower() if ch in 'aeiou')

66. Rotate list by k positions.

python

def rotate(lst, k):
    k = k % len(lst)
    return lst[-k:] + lst[:-k]

67. Check if a number is prime.

python

def is_prime(n):
    if n < 2: return False
    for i in range(2, int(n**0.5) + 1):
        if n % i == 0: return False
    return True

68. Fibonacci series (generator).

python

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

69. Find missing number in list [0..n].

python

n = len(nums)
expected = n*(n+1)//2
return expected - sum(nums)

70. Group anagrams together.

python

from collections import defaultdict
groups = defaultdict(list)
for word in words:
    key = ''.join(sorted(word))
    groups[key].append(word)

🔹 Part 7: Debugging, Testing, Best Practices (5+ questions)

71. How to debug Python code?

  • print()
  • pdb (Python debugger): pdb.set_trace()
  • breakpoint() (Python 3.7+)
  • Logging, IDE debuggers

72. What is pytest?

Testing framework.

python

def test_addition():
    assert 1 + 1 == 2

73. What is unittest.mock?

Replace parts of system under test.

python

from unittest.mock import MagicMock
mock = MagicMock(return_value=10)

74. What is blackflake8isort?

  • black: code formatter
  • flake8: linter
  • isort: sorts imports

75. What is pre-commit?

Git hook manager to run checks before commit.


76. How to profile Python code?

python

import cProfile
cProfile.run('my_function()')

77. What is __pycache__?

Folder containing compiled bytecode (.pyc files) for performance.

Here is another a comprehensive list of 80+ Python interview questions and detailed answers, categorized for clarity. This covers beginner to advanced topics, based on common questions from technical interviews (FAANG-level and general software roles) as of 2025-2026.

1. Python Basics & Fundamentals (Questions 1-15)

1. What is Python? What are its key features? Python is a high-level, interpreted, dynamically-typed, general-purpose programming language. Key features include: simple readable syntax, dynamic typing, automatic memory management (garbage collection), extensive standard library (“batteries included”), cross-platform, support for multiple paradigms (OOP, functional, procedural), and a huge ecosystem (NumPy, Pandas, Django, etc.).

2. Is Python compiled or interpreted? Python is both. Source code is compiled to bytecode (.pyc files) by the CPython interpreter, which is then executed by the Python Virtual Machine (PVM). It is generally considered interpreted because execution happens line-by-line at runtime.

3. What is the difference between a list and a tuple?

  • List: Mutable (can change), ordered, allows duplicates, slower.
  • Tuple: Immutable (cannot change after creation), ordered, allows duplicates, faster, hashable (can be dict keys). Use tuples for fixed data (e.g., coordinates) and lists for dynamic collections.

4. Explain mutable vs immutable objects with examples. Mutable: Can be changed in place (list, dict, set).

Python

lst = [1, 2]
lst.append(3)  # Modifies original

Immutable: Cannot be changed (int, float, str, tuple). Operations create new objects.

Python

s = "hello"
s = s + " world"  # New string created

5. What are Python’s built-in data types? Numeric: int, float, complex. Sequence: str, list, tuple, range. Mapping: dict. Set: set, frozenset. Boolean: bool. NoneType: None. Binary: bytes, bytearray, memoryview.

6. How do you concatenate two lists?

Python

list1 + list2
list1.extend(list2)
[*list1, *list2]  # Python 3.5+

Or use itertools.chain.

7. Explain list comprehensions with an example. Concise way to create lists:

Python

squares = [x**2 for x in range(10) if x % 2 == 0]
# [0, 4, 16, 36, 64]

8. What is the difference between == and is? == checks value equality. is checks identity (same object in memory).

Python

a = [1,2]; b = [1,2]
a == b  # True
a is b  # False

9. What are *args and **kwargs? *args: Variable number of positional arguments (tuple). **kwargs: Variable number of keyword arguments (dict).

Python

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

10. Explain global and local variables. Local: Defined inside function. Global: Defined outside; use global keyword to modify inside function. nonlocal for nested functions.

11. What is a lambda function? Anonymous single-expression function.

Python

add = lambda x, y: x + y

12. Difference between range() and xrange() (Python 2) / behavior in Python 3. In Python 3, range() returns an immutable sequence object (like xrange in Py2) that generates numbers on demand (memory efficient).

13. How does Python handle memory management?

  • Private heap for objects.
  • Reference counting + cyclic garbage collector.
  • gc module for control. Memory is automatically freed when reference count reaches zero.

14. What is PEP 8? Official style guide for Python code (naming, indentation, line length=79, etc.).

15. Explain dir() and help(). dir(obj): Lists attributes/methods. help(obj): Shows documentation.

2. Data Structures (Questions 16-30)

16. Difference between list, tuple, set, dict.

  • List: Ordered, mutable, duplicates OK.
  • Tuple: Ordered, immutable, duplicates OK.
  • Set: Unordered, mutable, no duplicates.
  • Dict: Ordered (Python 3.7+), mutable, unique keys.

17. How to remove duplicates from a list while preserving order?

Python

list(dict.fromkeys(lst))  # Python 3.7+
# or
seen = set(); [x for x in lst if not (x in seen or seen.add(x))]

18. Explain dictionary comprehension.

Python

{x: x**2 for x in range(5)}

19. What are sets used for? Membership testing, removing duplicates, mathematical set operations (union, intersection).

20. How does a dict work internally? Hash table. Keys are hashed; handles collisions with open addressing.

21. Difference between deepcopy and shallow copy. copy.copy(): Shallow (references nested objects). copy.deepcopy(): Recursive copy of all nested objects.

22-30. Common operations (e.g., reverse list: lst[::-1] or lst.reverse(); sort: sorted() vs list.sort(); merge dicts: dict1 | dict2 in 3.9+).

3. OOP in Python (Questions 31-45)

31. What is OOP? Key pillars? Object-Oriented Programming. Pillars: Encapsulation, Inheritance, Polymorphism, Abstraction.

32. What is __init__? Constructor method called on object creation.

33. Difference between class and instance variables. Class: Shared by all instances. Instance: Unique to each object.

34. Explain inheritance and multiple inheritance. Child class inherits from parent(s). Python uses Method Resolution Order (MRO) via C3 linearization (Class.__mro__).

35. What are magic/dunder methods? Give examples. __str__, __repr__, __len__, __getitem__, __add__, etc. Allow operator overloading.

36. Difference between method overriding and overloading. Overriding: Same method name in child (runtime polymorphism). Python doesn’t support traditional overloading (use defaults or *args).

37. What is encapsulation? Bundling data and methods; achieved via _ (protected) and __ (name mangling for private).

38. Class method vs static method vs instance method.

  • Instance: Takes self.
  • Class: @classmethod, takes cls.
  • Static: @staticmethod, no implicit first arg.

39. What is abstraction? Hiding implementation details (use ABC from abc module).

40. Explain super(). Calls parent class method.

41-45. Topics like @property, descriptors, metaclasses basics.

4. Functions, Iterators, Generators, Decorators (Questions 46-60)

46. What is an iterator? Object with __iter__() and __next__().

47. What are generators? Functions using yield that return iterators lazily (memory efficient).

48. Generator expression vs list comprehension. Generator: Lazy ((x**2 for x in range(10))). List: Eager.

49. What are decorators? Functions that modify other functions/classes without changing their code. Use @decorator. Example: timing decorator, logging.

50. How do decorators work internally? They take a function, return a wrapper function.

51. What is functools.wraps? Preserves original function metadata in decorators.

52. Explain closures. Function that remembers enclosing scope variables.

53. What is monkey patching? Dynamically modifying code at runtime (e.g., replacing methods).

54-60. Partial functions, map, filter, reduce, context managers (with statement, __enter__/__exit__).

5. Exception Handling & Modules (Questions 61-70)

61. How does exception handling work? try-except-else-finally. Custom exceptions by inheriting Exception.

62. Difference between Exception and BaseException. Exception for catchable errors; BaseException includes SystemExit, KeyboardInterrupt.

63. What are modules and packages? Module: .py file. Package: Directory with __init__.py.

64. Explain __name__ == “__main__”. Checks if file is run directly or imported.

6. Advanced Topics (Questions 71-80+)

71. What is GIL (Global Interpreter Lock)? Mutex preventing multiple native threads from executing Python bytecodes simultaneously. Limits CPU-bound multithreading. Use multiprocessing or async for concurrency.

72. Difference between threading and multiprocessing. Threading: Shared memory, GIL-limited. Multiprocessing: Separate processes, bypasses GIL.

73. What is async/await? For I/O-bound concurrency (asyncio).

74. Explain context variables and contextlib.

75. What are metaclasses? Classes of classes (type is the default metaclass). Used for advanced customization.

76. How does Python’s pickle work? Serialization/deserialization. Security risks with untrusted data.

77. Explain memory views and buffer protocol.

78. What is walrus operator := (Python 3.8+)? Assignment expression.

79. Common coding problems (e.g., two-sum with dict, reverse string, Fibonacci with memoization, FizzBuzz, anagrams with collections.Counter).

80. Performance tips: Use collections.deque for queues, avoid + in loops for strings (use join), profile with cProfile.

81+. Role-specific: Pandas (DataFrames, groupby), NumPy (arrays vs lists), web (Flask/Django views, ORM), testing (pytest fixtures, mocking).

Preparation Tips

Know standard library deeply (collections, itertools, functools).

Practice coding on LeetCode/HackerRank (focus on medium problems).

Understand time/space complexity.

Be ready to explain trade-offs and write clean code.

🤞 Sign up for our newsletter!

We don’t spam! Read more in our privacy policy

Scroll to Top