Guide Python Intermediate

8.11 Memory and Performance

Why every type conversion creates a brand-new object, the cost of re-converting the same value inside a loop, and why converting to a heavier type than needed wastes memory.

2 min read

Object Creation During Conversion

Every conversion call (int(x), str(x), …) creates a brand-new object — it never modifies the original in place, consistent with immutability (see 5.9 Mutable vs Immutable Types). The original value remains unchanged and independently referenced until nothing points to it anymore.

Performance Considerations

Converting inside a tight loop repeats the allocation cost every iteration — if the same value is converted many times, convert it once and reuse the result instead.

# Wasteful: re-converts the same value every iteration
for _ in range(1000):
    threshold = int(config["threshold"])

# Better: convert once, reuse
threshold = int(config["threshold"])
for _ in range(1000):
    ...    # use threshold directly

Memory Usage

Different types have different memory footprints for logically similar data — e.g. a tuple is generally more compact than an equivalent list. Converting to a heavier type unnecessarily wastes memory at scale.

Quick Interview Answer

“Every conversion allocates a brand-new object — nothing is ever modified in place, since Python’s conversions produce independent values consistent with how immutability works. The practical performance implication is to convert once and reuse the result, rather than re-converting the same value on every loop iteration, which repeats the allocation cost for no benefit. It’s also worth choosing the lightest type that actually fits the use case — converting to a heavier structure than needed wastes memory at scale for no functional gain.”

Common Mistakes

  • Re-running a conversion inside a loop body on a value that never changes — an easy, invisible performance cost that grows with iteration count.
  • Converting to a mutable collection (like list) purely out of habit when an immutable, more compact one (tuple) would serve the same purpose.

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form