Python Interview Questions
1. What are Python's key features?
- Easy to learn and use: Python has a simple, readable syntax.
- Interpreted Language: Python code is executed line by line.
- Dynamically Typed: No need to declare data types; Python detects them automatically.
- Object-Oriented: Supports classes, inheritance, and encapsulation.
- Extensive Libraries: Includes modules for math, OS, web, databases, machine learning, etc.
- Portable: Code written in one OS can run on another.
- Open Source: Freely available and supported by a strong community.
2. What is the difference between a list and a tuple in Python?
Feature | List | Tuple |
---|---|---|
Mutability | Mutable (can be changed) | Immutable (cannot be changed) |
Syntax | [] (e.g. [1, 2]) | () (e.g. (1, 2)) |
Performance | Slower due to flexibility | Faster due to immutability |
Use Cases | Data that may change | Fixed collections like constants |
3. How is memory managed in Python?
- Python uses a private heap to store objects and data structures.
- Automatic garbage collection reclaims memory from unused objects.
- Reference counting and the cyclic garbage collector manage memory.
- Developers can use the gc module to interact with the collector.
4. What are Python's data types?
- Numeric: int, float, complex
- Sequence: list, tuple, range
- Text: str
- Set: set, frozenset
- Mapping: dict
- Boolean: bool
- Binary: bytes, bytearray, memoryview
- NoneType: None
5. What is PEP 8 and why is it important?
- PEP 8 is the official style guide for Python code.
- Promotes readability and consistency across the Python community.
- Covers naming conventions, indentation (4 spaces), line length, imports, etc.
- Following PEP 8 ensures maintainable and professional code.
6. What is the difference between is and == in Python?
== checks value equality (do the objects have the same data?).
is checks identity equality (are both variables pointing to the same object in memory?).
a = [1, 2]
b = [1, 2]
print(a == b) # True
print(a is b) # False
7. What are Python's mutable and immutable data types?
- Mutable (can be changed): list, dict, set, bytearray
- Immutable (cannot be changed): int, float, str, tuple, frozenset, bytes
8. What are *args and **kwargs?
- *args: Allows passing a variable number of non-keyword arguments to a function.
- **kwargs: Allows passing a variable number of keyword arguments.
def example(*args, **kwargs):
print(args) # tuple
print(kwargs) # dictionary
9. What is the difference between Python 2 and Python 3?
Feature | Python 2 | Python 3 |
---|---|---|
Print Syntax | print "hello" | print("hello") |
Unicode | Not default | Default string type |
Division | Integer division | True division by default |
Support | Ended Jan 2020 | Actively supported |
10. How does Python handle type conversion?
- Implicit Conversion: Automatically done by Python (e.g., int to float).
- Explicit Conversion: Done manually using functions like int(), float(), str(), etc.
a = 5
b = 2.0
c = a + b # Implicitly converted to float
Intermediate Level
11. What are Python decorators and how are they used?
A decorator is a function that adds functionality to another function without modifying its code.
Typically used for logging, access control, memoization, etc.
def decorator(func):
def wrapper():
print("Before")
func()
print("After")
return wrapper
@decorator
def say_hello():
print("Hello")
12. What is the difference between shallow copy and deep copy?
- Shallow Copy: Copies outer object, not nested objects. (copy.copy())
- Deep Copy: Copies everything recursively. (copy.deepcopy())
import copy
a = [[1, 2], [3, 4]]
b = copy.copy(a) # changes in inner lists affect both
c = copy.deepcopy(a) # fully independent copy
13. What is a Python generator? How is it different from an iterator?
- Generators use yield to produce a sequence of results lazily.
- Generators are a type of iterator but are more memory efficient.
def gen():
yield 1
yield 2
Generators do not store all values in memory; they generate one value at a time.
14. Explain the Global Interpreter Lock (GIL).
- GIL is a mutex that allows only one thread to execute at a time in the CPython interpreter.
- It makes multi-threading limited for CPU-bound tasks but is fine for I/O-bound operations.
- Alternative: use multiprocessing instead of threads for CPU-heavy tasks.
15. What are Python's lambda functions?
- A lambda function is a small anonymous function defined using the lambda keyword.
- Syntax: lambda arguments: expression
add = lambda x, y: x + y
print(add(2, 3)) # Output: 5
16. How does Python handle exception handling? Give examples.
- Uses try, except, finally, and else blocks.
- Catches and handles errors gracefully.
try:
result = 10 / 0
except ZeroDivisionError:
print("Can't divide by zero")
finally:
print("Cleanup")
17. What are list comprehensions and how do they work?
A concise way to create lists.
squares = [x**2 for x in range(5)]
# Output: [0, 1, 4, 9, 16]
Supports conditions: [x for x in range(10) if x % 2 == 0]
18. Explain Python's with statement and context managers.
- Used for resource management (like files), ensuring cleanup.
- A context manager implements __enter__ and __exit__.
with open('file.txt') as f:
data = f.read()
# File is automatically closed
19. What is the purpose of __init__.py file?
- Marks a directory as a Python package.
- Can also include initialization code for the package.
- Required in Python 2, optional in Python 3 for basic package creation.
20. What are Python modules and packages? How do you import them?
- Module: A .py file containing Python code (functions, classes).
- Package: A folder containing modules and an optional __init__.py.
Importing:
import math
from datetime import datetime
import mypackage.mymodule