Monday, 3 March 2025

 

Python Interview Questions and Answers

Python is one of the most widely used programming languages today. Whether you’re preparing for a job interview or just sharpening your skills, here are the top 50 Python interview questions with answers to help you succeed.


🔹 Basic Python Interview Questions

1. What is Python?

Python is an interpreted, high-level, dynamically typed programming language known for its readability and ease of use.

2. What are the key features of Python?

  • Easy to learn and read
  • Open-source and community-supported
  • Supports object-oriented and functional programming
  • Automatic memory management (Garbage Collection)
  • Extensive standard library

3. What is the difference between Python 2 and Python 3?

FeaturePython 2Python 3
Print Statementprint "Hello"print("Hello")
Integer Division5/2 = 25/2 = 2.5
UnicodeStrings are ASCIIStrings are Unicode by default

4. What are Python’s built-in data types?

  • Numbers: int, float, complex
  • Sequence: list, tuple, range
  • Text: str
  • Set types: set, frozenset
  • Mapping: dict
  • Boolean: bool

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

FeatureList (list)Tuple (tuple)
MutabilityMutable (can be changed)Immutable (cannot be changed)
PerformanceSlowerFaster
Syntax[]()

🔹 Intermediate Python Interview Questions

6. What is a Python dictionary?

A dictionary is a collection of key-value pairs:

python
my_dict = {"name": "Alice", "age": 25} print(my_dict["name"]) # Output: Alice

7. What is list comprehension in Python?

List comprehension provides a concise way to create lists:

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

8. Explain Python’s memory management.

  • Reference Counting – Python keeps track of how many references exist for an object.
  • Garbage Collection – Removes objects with zero references.

9. What is the difference between deepcopy() and copy()?

  • copy.copy() creates a shallow copy (references nested objects).
  • copy.deepcopy() creates a deep copy (fully independent copy).

10. What is the difference between is and ==?

  • is checks object identity (memory location).
  • == checks values.

🔹 Advanced Python Interview Questions

11. What is a Python generator?

A generator returns an iterator using yield:

python
def my_gen(): yield 1 yield 2 yield 3 gen = my_gen() print(next(gen)) # Output: 1

12. What is the with statement used for?

Used for resource management, like opening files:

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

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

  • map() – Applies a function to all items.
  • filter() – Filters elements based on a condition.
  • reduce() – Reduces a list to a single value.
python
from functools import reduce nums = [1, 2, 3, 4] print(list(map(lambda x: x*2, nums))) # [2, 4, 6, 8] print(list(filter(lambda x: x%2==0, nums))) # [2, 4] print(reduce(lambda x, y: x+y, nums)) # 10

14. What are Python decorators?

Decorators modify functions without changing their definition:

python
def decorator(func): def wrapper(): print("Before function call") func() print("After function call") return wrapper @decorator def say_hello(): print("Hello!") say_hello()

15. What is multithreading in Python?

Python supports multithreading using the threading module:

python
import threading def print_numbers(): for i in range(5): print(i) t = threading.Thread(target=print_numbers) t.start()

16. What is a lambda function in Python?

A lambda function is an anonymous function defined using the lambda keyword. It can take multiple arguments but has only one expression.

python
add = lambda x, y: x + y print(add(3, 5)) # Output: 8

17. What is the difference between @staticmethod and @classmethod?

Feature@staticmethod@classmethod
Access to self❌ No❌ No
Access to cls❌ No✅ Yes
Can modify class variables?❌ No✅ Yes
Bound to class or instance?ClassClass
python
class Example: class_variable = "Hello" @staticmethod def static_method(): print("Static method called") @classmethod def class_method(cls): print("Class method called:", cls.class_variable)

18. What is the purpose of the pass statement?

The pass statement acts as a placeholder for future code. It prevents syntax errors.

python
def function(): pass # Placeholder for future code

19. Explain Python’s self keyword in classes.

The self keyword represents the current instance of the class. It is used to access instance variables and methods.

python
class Person: def __init__(self, name): self.name = name # Using 'self' to assign instance variable def greet(self): print(f"Hello, my name is {self.name}")

20. How do you handle exceptions in Python?

Python uses try-except blocks for exception handling.

python
try: x = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") finally: print("Execution completed.")

21. What is __init__.py used for?

It marks a directory as a Python package and allows imports from that directory.


22. How does Python implement memory management?

  • Automatic garbage collection using reference counting and cyclic garbage collector.
  • Memory allocation using Python's private heap space.

23. What is the difference between break, continue, and pass?

KeywordFunction
breakExits the loop completely
continueSkips the current iteration and continues the loop
passDoes nothing (used as a placeholder)

24. What is *args and **kwargs in function definitions?

  • *args allows a function to accept any number of positional arguments.
  • **kwargs allows a function to accept any number of keyword arguments.
python
def example(*args, **kwargs): print(args) # Tuple of arguments print(kwargs) # Dictionary of keyword arguments

25. How can you merge two dictionaries in Python?

python
dict1 = {"a": 1, "b": 2} dict2 = {"c": 3, "d": 4} # Method 1 (Python 3.5+) merged_dict = {**dict1, **dict2} # Method 2 (Python 3.9+) merged_dict = dict1 | dict2

26. Explain Python’s set data type.

A set is an unordered collection of unique elements.

python
my_set = {1, 2, 3, 4, 4} print(my_set) # Output: {1, 2, 3, 4}

27. How can you swap two variables in Python without a temporary variable?

python
a, b = 5, 10 a, b = b, a print(a, b) # Output: 10 5

28. How do you sort a list in Python?

python
numbers = [3, 1, 4, 1, 5] numbers.sort() # In-place sorting print(numbers) # Output: [1, 1, 3, 4, 5]

29. How do you convert a string into a list?

python
string = "hello" list_version = list(string) print(list_version) # Output: ['h', 'e', 'l', 'l', 'o']

30. What is __name__ == "__main__" used for?

It ensures that a script runs only when executed directly, not when imported.

python
if __name__ == "__main__": print("Script is running directly")

31. What is the difference between range() and xrange()?

  • range() – Returns a list (Python 2 and 3).
  • xrange() – Returns a generator (Python 2 only, removed in Python 3).

32. How do you implement a stack or queue in Python?

Using collections.deque:

python
from collections import deque stack = deque() stack.append(1) stack.pop()

33. Explain Python’s super() function.

Used to call a parent class’s method.

python
class Parent: def greet(self): print("Hello from Parent") class Child(Parent): def greet(self): super().greet() # Call parent method print("Hello from Child")

34. How do you read and write files in Python?

python
with open("file.txt", "w") as file: file.write("Hello, world!") with open("file.txt", "r") as file: print(file.read())

35. How can you generate a random number in Python?

python
import random print(random.randint(1, 10)) # Random number between 1 and 10

36. Explain the difference between global and nonlocal keywords.

  • global allows modifying a global variable inside a function.
  • nonlocal allows modifying a variable from an enclosing scope.

37. What is method overloading and method overriding in Python?

  • Overloading – Python does not support traditional overloading but allows default parameters.
  • Overriding – A child class redefines a method from the parent class.

38. What is monkey patching in Python?

Modifying a module/class at runtime.

python
import some_module some_module.function = new_function # Monkey patching

39. Explain Python’s functools module.

It provides utilities like lru_cache, partial, and reduce().

python
from functools import lru_cache @lru_cache(maxsize=128) def expensive_function(x): return x * x

40. What is pytest and how is it used?

pytest is a testing framework for Python.

python
def test_sum(): assert sum([1, 2, 3]) == 6

Run tests with:

sh
pytest test_script.py

  Python Interview Questions and Answers Python is one of the most widely used programming languages today. Whether you’re preparing for a j...