Table of Contents
1. What is the difference between deepcopy and copy? When does it matter?
A shallow copy (copy.copy) creates a new object but does not recursively copy nested objects. A deep copy (copy.deepcopy) creates a completely independent copy of the original object, including all nested objects.Explanation:
If a list contains other lists, modifying a nested list in a shallow copy will also affect the original. Deep copy avoids this issue.
Example:
# Python program to show difference
# between shallow copy and deep copy
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
shallow[0][0] = 99
print("Original:", original)
print("Shallow:", shallow)
print("Deep:", deep)
Output:
Original: [[99, 2], [3, 4]]
Shallow: [[99, 2], [3, 4]]
Deep: [[1, 2], [3, 4]]
2. Why are Python sets faster than lists for membership checks?
Sets use hash tables, while lists use linear search.Explanation:
Checking x in list takes O(n) time, whereas x in set takes average O(1) time due to hashing.
Table Comparison
| Operation | List | Set |
|---|---|---|
| Membership Check | It takes linear time because each element must be checked one by one. | It takes constant time on average because hashing allows direct access. |
| Order | Lists maintain insertion order. | Sets do not maintain order. |
| Duplicates | Lists allow duplicate values. | Sets automatically remove duplicates. |
3. What are Python generators and why are they used in large-scale systems?
Generators are functions that yield values one at a time using the yield keyword instead of returning all values at once.Explanation:
Generators are memory-efficient because they do not store the entire dataset in memory.
Example:
# Python program to show generator
def count_up_to(n):
i = 1
while i = n:
yield i
i += 1
for num in count_up_to(5):
print(num)
Output:
1
2
3
4
5
4. What is the difference between is and ==?
== checks value equality, while is checks object identity.Explanation:
Two variables may have the same value but refer to different objects in memory.
Example:
# Python program to show is and == a = [1, 2, 3] b = [1, 2, 3] # True print(a == b) # False print(a is b)Output:
True
False
5. Explain Python’s Global Interpreter Lock (GIL) and its impact.
The GIL ensures that only one thread executes Python bytecode at a time.Explanation:
It simplifies memory management but limits true parallelism in CPU-bound tasks.
Key Insight:
- Multithreading is useful for I/O-bound tasks.
- Multiprocessing is preferred for CPU-bound tasks.
6. What is monkey patching? When is it used?
Monkey patching means modifying or extending code at runtime.Explanation:
It is often used in testing or temporarily fixing bugs without modifying source code.
# Python program to show
# monkey patching
class A:
def greet(self):
return "Hello"
def new_greet(self):
return "Hi"
A.greet = new_greet
obj = A()
print(obj.greet())
Output:
Hi
7. How does Python handle memory management?
Python uses reference counting and garbage collection.Explanation:
- Reference counting tracks how many references point to an object
- Garbage collector removes cyclic references
8. What is the difference between @staticmethod, @classmethod, and instance methods?
| Method | Description |
|---|---|
| Instance method | It takes self and works with object data. |
| Class method | It takes cls and works with class-level data. |
| Static method | It does not take self or cls and behaves like a normal function inside a class. |
# Python program to show static method,
# class method, and instance method
class Demo:
def instance_method(self):
return "Instance"
@classmethod
def class_method(cls):
return "Class"
@staticmethod
def static_method():
return "Static"
obj = Demo()
print(obj.instance_method())
print(Demo.class_method())
print(Demo.static_method())
Output:
Instance
Class
Static
9. What are Python decorators and how are they used in real projects?
Decorators are functions that modify the behavior of other functions.Explanation:
They are widely used for logging, authentication, and caching.
# Python program to show decorators
def decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@decorator
def say_hello():
print("Hello!")
say_hello()
Output:
Before function call
Hello!
After function call
10. What is the difference between multiprocessing and multithreading?
| Feature | Multithreading | Multiprocessing |
|---|---|---|
| Execution | It runs threads within a single process. | It runs multiple processes. |
| GIL impact | It is affected by GIL. | It bypasses GIL. |
| Use case | It is best for I/O-bound tasks. | It is best for CPU-bound tasks. |
11. How do you handle large files in Python without loading them fully?
To handle the large files in Python without loading them fully, we can use file iteration or generators.Example:
with open("large_file.txt", "r") as file:
for line in file:
print(line.strip())
Explanation:This reads one line at a time instead of loading the full file into memory.
12. What is __slots__ and why is it used?
__slots__ restricts dynamic attribute creation and saves memory.
# Python program to show _slots_
class Person:
__slots__ = ['name', 'age']
p = Person()
p.name = "John"
p.age = 25
Explanation:It reduces memory usage in large-scale applications with many objects.
13. What are Python context managers?
They manage resources automatically using with.Example:
with open("file.txt", "w") as f:
f.write("Hello")
Explanation:It ensures files are properly closed even if errors occur.
14. How does Python handle exceptions internally?
Python uses a stack-based mechanism where exceptions propagate up the call stack until handled.Example:
try:
x = 10 / 0
except ZeroDivisionError:
print("Error occurred")
15. What is the difference between iterable and iterator?
An iterable is an object you can loop over, while an iterator is an object that keeps track of iteration state.# Python program to show iterable and iterator nums = [1, 2, 3] it = iter(nums) print(next(it)) print(next(it))Output:
1
2
Conclusion
Python interviews today focus less on theory and more on how you apply concepts in real situations. What matters most is your ability to write clean code, think logically, and choose efficient approaches.If you practice real problems, understand how Python works internally, and explain your solutions clearly, you’ll stand out in placements.
Frequently Asked Questions
1. Are basic Python questions still asked in placements?2. Do companies ask tricky Python internals questions?Yes, but they are usually combined with practical scenarios rather than direct theory.
3. Is coding required along with theory?Yes, especially product-based companies and startups.
4. How important is Python for placements?Yes, most interviews include both conceptual and coding rounds.
5. How can I prepare effectively?It is highly important, especially for backend, data, and automation roles.
Practice real problems, understand internals, and simulate interview scenarios.
0 Comments