30 Most Common Python Interview Questions and Answers.

By | March 19, 2025

Here are 30 of the most common Python interview questions along with concise answers and examples:

1. What is Python?

Python is a high-level, interpreted programming language known for its readability and simplicity. It supports multiple programming paradigms including procedural, object-oriented, and functional programming.

# Simple Python example
print("Hello, World!")

2. What are the key features of Python?

  • Interpreted language
  • Dynamically typed
  • Object-oriented
  • Extensive standard library
  • Easy to read and write
  • Cross-platform
  • Free and open-source

3. What is the difference between lists and tuples?

Lists are mutable (can be changed) while tuples are immutable (cannot be changed after creation).

# List example
my_list = [1, 2, 3]
my_list[0] = 10  # Valid

# Tuple example
my_tuple = (1, 2, 3)
# my_tuple[0] = 10  # This would raise an error

4. How do you handle exceptions in Python?

Using try-except blocks:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
finally:
    print("This always executes")

5. What is a dictionary in Python?

A dictionary is an unordered collection of key-value pairs.

student = {
    "name": "John",
    "age": 25,
    "courses": ["Math", "Computer Science"]
}
print(student["name"])  # Output: John

6. What is the difference between == and is operators?

== checks if values are equal, while is checks if two references point to the same object in memory.

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)

7. What are list comprehensions?

A concise way to create lists based on existing lists or other iterables.

numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
# squares = [1, 4, 9, 16, 25]

8. What is a lambda function?

A small anonymous function defined with the lambda keyword.

multiply = lambda x, y: x * y
print(multiply(5, 3))  # Output: 15

9. What is PEP 8?

PEP 8 is Python’s style guide that provides coding conventions for writing clear and consistent Python code.

10. How do you create a class in Python?

Using the class keyword:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        
    def greet(self):
        return f"Hello, my name is {self.name}"

person = Person("Alice", 30)
print(person.greet())  # Output: Hello, my name is Alice

11. What is inheritance in Python?

Inheritance allows a class to inherit attributes and methods from another class.

class Student(Person):
    def __init__(self, name, age, student_id):
        super().__init__(name, age)
        self.student_id = student_id

12. What is the difference between __str__ and __repr__?

__str__ returns a string representation for end-users, while __repr__ returns a string representation for developers.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    
    def __str__(self):
        return f"Point at ({self.x}, {self.y})"
    
    def __repr__(self):
        return f"Point({self.x}, {self.y})"

13. What are decorators in Python?

Decorators are functions that modify the behavior of other functions or methods.

def log_function(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

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

result = add(3, 5)  # Output: Calling add, then 8

14. What is the Global Interpreter Lock (GIL)?

The GIL is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecode at once. It can limit the performance of multi-threaded Python programs.

15. How do you handle file operations in Python?

Using the open() function with context managers:

# Writing to a file
with open("example.txt", "w") as file:
    file.write("Hello, World!")

# Reading from a file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)  # Output: Hello, World!

16. What is the difference between append() and extend() for lists?

append() adds a single element to the end of a list, while extend() adds multiple elements from an iterable.

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

17. What is a generator in Python?

A generator is a function that returns an iterator that produces a sequence of values when iterated over.

def count_up_to(n):
    i = 1
    while i <= n:
        yield i
        i += 1

for number in count_up_to(5):
    print(number)  # Output: 1, 2, 3, 4, 5

18. What is the difference between range() and xrange() in Python?

In Python 2, range() returns a list while xrange() returns an iterator. In Python 3, range() returns an iterator and xrange() no longer exists.

19. How do you copy objects in Python?

Using the copy module for shallow copies and deepcopy for deep copies:

import copy

original = [1, [2, 3]]
shallow_copy = copy.copy(original)
deep_copy = copy.deepcopy(original)

original[1][0] = 99
print(shallow_copy)  # [1, [99, 3]] (inner list is affected)
print(deep_copy)     # [1, [2, 3]] (completely independent)

20. What are Python modules and packages?

A module is a single Python file containing code. A package is a directory containing multiple modules and a special __init__.py file.

21. How do you implement multithreading in Python?

Using the threading module:

import threading

def print_numbers():
    for i in range(5):
        print(i)

thread = threading.Thread(target=print_numbers)
thread.start()
thread.join()

22. What is the difference between __init__ and __new__ methods?

__new__ is responsible for creating and returning a new instance of the class, while __init__ initializes the instance after it’s created.

23. How do you handle virtual environments in Python?

Using tools like venv or virtualenv:

# Create a virtual environment
python -m venv myenv

# Activate it (on Windows)
myenv\Scripts\activate

# Activate it (on macOS/Linux)
source myenv/bin/activate

24. What is the *args and **kwargs syntax in Python?

*args allows a function to accept any number of positional arguments, and **kwargs allows it to accept any number of keyword arguments.

def example_function(*args, **kwargs):
    print(f"Positional arguments: {args}")
    print(f"Keyword arguments: {kwargs}")

example_function(1, 2, 3, name="John", age=25)

25. How do you implement function overloading in Python?

Python doesn’t support function overloading directly, but you can use default arguments or variable-length arguments instead.

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

26. What is the difference between del, remove(), and pop() for lists?

  • del list[index] removes an item at a specific index
  • list.remove(value) removes the first occurrence of a value
  • list.pop(index) removes and returns an item at a specific index (defaults to last item)

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

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

28. How do you implement a singleton pattern in Python?

Using a class with a class variable to store the instance:

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

29. What is the difference between __str__ and __repr__ methods?

__str__ is meant for user-friendly string representation, while __repr__ is meant for developers and debugging.

30. How do you use list slicing in Python?

Using the syntax list[start:stop:step]:

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:7])     # [2, 3, 4, 5, 6]
print(numbers[::2])     # [0, 2, 4, 6, 8]
print(numbers[::-1])    # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Would you like me to explain any of these questions in more detail?

Thanks for reading!

Leave a Reply

Your email address will not be published. Required fields are marked *