Skip to content
C

Python Interview Questions

Memory Management Interview Questions

Reference counting, garbage collection, shallow vs deep copy, object identity, weak references, and context managers.

Question 1: How does Python manage memory?

Ans

Python implementations manage objects in a private runtime memory space. CPython primarily uses reference counting plus a cyclic garbage collector to reclaim unreachable reference cycles.

Example

python
a = {"x": 1} b = a del a print(b)

Important Point

Memory-management details are implementation-specific; avoid presenting CPython internals as universal Python language rules.

Question 2: What is reference counting?

Ans

In CPython, objects maintain a reference count representing active references. When the count reaches zero, the object's memory can generally be reclaimed immediately.

Example

python
import sys x = [] print(sys.getrefcount(x))

Important Point

`getrefcount()` itself temporarily creates another reference, so its result is higher than expected.

Question 3: What is garbage collection?

Ans

Python's cyclic garbage collector detects groups of objects that reference each other but are no longer reachable from live program roots.

Example

python
import gc print(gc.isenabled())

Important Point

Garbage collection does not replace explicit management of external resources such as files or database connections.

Question 4: What is shallow copy?

Ans

A shallow copy creates a new outer container but keeps references to the same nested objects.

Example

python
import copy original = [[1, 2], [3, 4]] clone = copy.copy(original) clone[0].append(9) print(original)

Important Point

Changes to nested mutable objects can therefore appear through both structures.

Question 5: What is deep copy?

Ans

A deep copy recursively copies nested objects according to the copy module's rules, producing a more independent object graph.

Example

python
import copy original = [[1, 2]] clone = copy.deepcopy(original) clone[0].append(9) print(original, clone)

Important Point

Deep copying can be expensive and may not be appropriate for objects holding external resources or complex graphs.

Question 6: What is id()?

Ans

id(obj) returns an integer identifying an object for its lifetime. In CPython it commonly corresponds to the object's memory address, but that is an implementation detail.

Example

python
x = object() print(id(x))

Important Point

Do not use id values as persistent identifiers.

Question 7: What is garbage collection vs resource cleanup?

Ans

Garbage collection reclaims memory for unreachable objects, while resource cleanup releases external resources such as file handles, sockets, locks, and database connections.

Example

python
with open("data.txt") as f: data = f.read()

Important Point

Use context managers or explicit close/release APIs for external resources instead of waiting for GC.

Question 8: What is a context manager?

Ans

A context manager defines setup and cleanup behavior around a block, normally through __enter__ and __exit__, and is used with the with statement.

Example

python
class Demo: def __enter__(self): print("start"); return self def __exit__(self, exc_type, exc, tb): print("cleanup") with Demo(): print("work")

Important Point

A context manager can also suppress an exception by returning true from `__exit__`, so that behavior should be deliberate.

Question 9: What is dataclass?

Ans

dataclasses.dataclass generates common methods for classes primarily used to store data, such as an initializer and representations, according to its configuration.

Example

python
from dataclasses import dataclass @dataclass class Student: name: str age: int print(Student("Amit", 25))

Important Point

A dataclass does not automatically make nested mutable data immutable.

Question 10: What is object identity?

Ans

Identity means whether two references refer to the exact same object. Python exposes identity comparison with is.

Example

python
a = [] b = a c = [] print(a is b) # True print(a is c) # False

Important Point

Use identity checks for singleton-like objects such as None, not ordinary value comparisons.

Question 11: What is garbage collector generation?

Ans

CPython's cyclic garbage collector historically groups tracked objects into generations so long-lived objects can be scanned differently from newly allocated ones.

Example

python
import gc print(gc.get_threshold())

Important Point

Exact GC implementation details can change between Python releases, so use them for explanation rather than hard-coded application assumptions.

Question 12: What is weakref?

Ans

The weakref module creates references that do not keep an object alive. Weak references are useful for caches and observer relationships where ownership should not be retained.

Example

python
import weakref class User: pass u = User() r = weakref.ref(u) print(r() is u)

Important Point

Not every object supports weak references; the class layout can affect support.

Question 13: What is contextlib?

Ans

contextlib contains helpers for building and composing context managers, including contextmanager, closing, and nullcontext.

Example

python
from contextlib import contextmanager @contextmanager def demo(): print("start") try: yield finally: print("cleanup") with demo(): print("work")

Important Point

Ensure cleanup is placed in a finally block inside generator-based context managers.

Question 14: What is copy.copy vs assignment?

Ans

Assignment creates another reference to the same object; copy.copy() creates a new outer object with shared nested references.

Example

python
import copy a = [[1]] b = a c = copy.copy(a) print(a is b, a is c)

Important Point

This distinction is fundamental when working with mutable containers.

Continue Your Preparation