Python
Interview Questions and Answers
Python
Interview Questions and Answers
Top Interview Questions and Answers on Python ( 2025 )
Common interview questions and answers related to Python. This can serve as a good preparation resource for interviews:
Basic Questions
1. What is Python?
- Answer: Python is an interpreted, high-level programming language that emphasizes code readability. It supports multiple programming paradigms, including procedural, object-oriented, and functional programming. Python has a large standard library and is known for its simplicity and efficiency.
2. What are the key features of Python?
- Answer:
- Easy to understand and learn
- Extensive libraries and frameworks
- Cross-platform compatibility
- Automatic memory management (garbage collection)
- Support for object-oriented and functional programming
- Dynamic typing
3. What is PEP 8?
- Answer: PEP 8 is the Python Enhancement Proposal that provides guidelines and best practices on how to write Python code. It covers naming conventions, indentation, line length, and more to promote readable and consistent code.
4. How do you manage memory in Python?
- Answer: Python uses automatic memory management through a built-in garbage collector, which recycles memory that is no longer in use by keeping track of reference counts and reclaiming memory when reference counts drop to zero.
5. What are lists and tuples in Python?
- Answer:
- Lists: Ordered, mutable collections of items that can hold different data types. Defined using square brackets `[]`.
- Tuples: Ordered, immutable collections of items that can also hold different data types. Defined using parentheses `()`.
Intermediate Questions
6. What is a Python decorator?
- Answer: A decorator is a function that modifies the behavior of another function or method. It is applied to a function using the `@decorator_name` syntax. Decorators are often used for logging, access control, and caching.
7. What is the difference between `deepcopy` and `shallow copy`?
- Answer:
- Shallow Copy: Creates a new object but inserts references into it to the objects found in the original. Changes to mutable objects will reflect in both copies.
- Deep Copy: Creates a new object and recursively adds copies of nested objects found in the original. Changes to mutable objects in the deep copy do not affect the original.
8. What is the Global Interpreter Lock (GIL)?
- Answer: The Global Interpreter Lock (GIL) is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecode simultaneously. This can be a limitation in CPU-bound multi-threaded programs.
9. How do you handle exceptions in Python?
- Answer: Exceptions in Python can be handled using try-except blocks. You can also use finally to execute code regardless of whether an exception occurred and raise to throw an exception.
```python
try:
# code that may raise an exception
except SomeException as e:
# handle the exception
finally:
# code that runs no matter what
```
10. What is the purpose of the `self` parameter in Python class methods?
- Answer: The `self` parameter refers to the instance of the class itself and allows access to its attributes and methods. It must be the first parameter of instance methods in a class definition.
Advanced Questions
11. What are generators in Python?
- Answer: Generators are a type of iterable that allow you to iterate over a sequence of values without storing them in memory at once. Generators are defined using the `yield` keyword and provide a lazy way to process large datasets.
12. What are lambda functions?
- Answer: Lambda functions are anonymous functions defined with the `lambda` keyword. They can take any number of arguments but can only have a single expression. They are often used for short, throwaway functions.
```python
lambda x: x * 2 # This creates a function that doubles the input
```
13. What is the difference between `__str__` and `__repr__`?
- Answer:
- `__str__`: Intended to provide a “pretty” string representation of an object that is more user-friendly.
- `__repr__`: Intended to provide an unambiguous string representation of the object that can be used for debugging. It should ideally return a string that can be used to recreate the object.
14. Explain list comprehension and provide an example.
- Answer: List comprehension is a concise way to create lists in Python. It consists of brackets containing an expression followed by a `for` clause, and may also include `if` clauses.
```python
squares = [x2 for x in range(10)] # Creates a list of squares from 0 to 9
```
15. What are context managers in Python?
- Answer: Context managers allow you to allocate and release resources precisely when you want. The most common use case is opening files, using the `with` statement to ensure proper cleanup.
```python
with open('file.txt', 'r') as file:
content = file.read()
```
Conclusion
This set of questions should provide a solid foundation for your preparation. Make sure to understand the concepts behind each question and practice coding examples where applicable. Good luck with your interview!
Advance Interview Questions and Answers on Python
Some advanced interview questions and answers on Python that delve deeper into the language's features, libraries, and best practices.
Advanced Python Interview Questions and Answers
1. What is metaprogramming in Python?
- Answer: Metaprogramming is the practice of writing code that manipulates code at runtime. In Python, this can be achieved using metaclasses, which are classes of a class that define how a class behaves. You can create custom behaviors for classes by defining a metaclass and overriding methods like `__new__` and `__init__`.
```python
class Meta(type):
def __new__(cls, name, bases, attrs):
attrs['new_attribute'] = 'value'
return super(Meta, cls).__new__(cls, name, bases, attrs)
class MyClass(metaclass=Meta):
pass
print(MyClass.new_attribute) # Outputs: 'value'
```
2. What is the difference between `@staticmethod` and `@classmethod`?
- Answer:
- `@staticmethod`: A method that does not require access to the class or instance. It behaves just like a normal function but belongs to the class's namespace.
- `@classmethod`: A method that takes the class as the first argument (`cls`). It can modify class state that applies across all instances of the class.
```python
class MyClass:
class_variable = 0
@classmethod
def increment(cls):
cls.class_variable += 1
@staticmethod
def static_method():
return "I'm a static method"
MyClass.increment()
print(MyClass.class_variable) # Outputs: 1
```
3. Explain the concept of decorators and give an example of a decorator that takes arguments.
- Answer: Decorators are a way to modify or extend the behavior of functions or methods. They are functions that return another function. A decorator that takes arguments can be implemented by nesting the decorator function within another function.
```python
def repeat(num_times):
def decorator_repeat(func):
def wrapper(*args, kwargs):
for _ in range(num_times):
result = func(*args, kwargs)
return result
return wrapper
return decorator_repeat
@repeat(3)
def greet(name):
print(f"Hello, {name}!")
greet("Alice") # Prints "Hello, Alice!" three times.
```
4. What are `__slots__` and what are their advantages?
- Answer: `__slots__` is a special variable in Python that can be used to define a fixed set of attributes for a class. By using `__slots__`, you can limit the attributes that instances of a class can have, which can result in memory savings and performance improvements.
```python
class Point:
__slots__ = ['x', 'y']
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
# p.z = 3 # This will raise an AttributeError since 'z' is not allowed in __slots__.
```
5. What is the difference between a shallow copy and a deep copy?
- Answer: A shallow copy creates a new object but inserts references into it to the objects found in the original, so it does not create copies of nested objects. A deep copy creates a new object and recursively copies all objects found in the original. You can create deep copies using the `copy` module.
```python
import copy
original = [[1, 2, 3], [4, 5, 6]]
shallow_copied = copy.copy(original)
deep_copied = copy.deepcopy(original)
shallow_copied[0][0] = 'X'
print(original) # Outputs: [['X', 2, 3], [4, 5, 6]]
print(deep_copied) # Outputs: [[1, 2, 3], [4, 5, 6]]
```
6. What are context managers, and how can you create a custom one?
- Answer: Context managers allow you to allocate and release resources precisely when you want. They are usually created using the `with` statement. You can create custom context managers using the `__enter__` and `__exit__` methods.
```python
class MyContextManager:
def __enter__(self):
print("Entering the context")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Exiting the context")
with MyContextManager() as manager:
print("Within the context")
```
7. How do you perform memory profiling in Python?
- Answer: Memory profiling can be performed using libraries such as `memory_profiler` and `objgraph`. You can use the `@profile` decorator from `memory_profiler` to profile the memory usage of specific functions.
```python
# To use memory_profiler, install it via pip: pip install memory_profiler
from memory_profiler import profile
@profile
def my_function():
a = [x for x in range(100000)]
return a
my_function()
```
8. Explain the use of the `async` and `await` keywords in Python.
- Answer: The `async` keyword is used to define an asynchronous function that can be paused to allow other code to run. The `await` keyword is used to call an async function, pausing execution until the awaited function is complete. This allows for non-blocking I/O operations.
```python
import asyncio
async def say_hello():
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(say_hello())
```
9. What are the differences between `iter()` and `next()`? How would you create a custom iterator?
- Answer: The `iter()` function returns an iterator object from an iterable, while the `next()` function retrieves the next item from the iterator. A custom iterator can be created by defining a class and implementing the `__iter__` and `__next__` methods.
```python
class MyIterator:
def __init__(self, limit):
self.limit = limit
self.counter = 0
def __iter__(self):
return self
def __next__(self):
if self.counter < self.limit:
self.counter += 1
return self.counter
else:
raise StopIteration
my_iter = MyIterator(5)
for number in my_iter:
print(number) # Outputs: 1 2 3 4 5
```
10. What are some common pitfalls to avoid when using Python?
- Answer:
- Mutable Default Arguments: Using mutable types (like lists or dictionaries) as default argument values can lead to unexpected behavior.
- Integer Caching: Be aware that small integers in Python are cached, which can lead to unexpected equality checks.
- Using `is` for Value Comparison: Use `==` for comparing values and `is` for comparing identities.
- Not Using Generators for Large Datasets: Using lists for large datasets instead of generators can lead to high memory usage.
By understanding these advanced concepts in Python, you'll be better prepared for technical interviews and able to tackle more complex programming challenges. Good luck!