Loading notes...
Loading notes...
B.Tech • Chapter 3
B.Tech level module on Deep Dive.
In Python, Strings are immutable sequences of Unicode code points, while Lists are mutable arrays of object references. Understanding their internal representation is key to writing memory-efficient applications.
Advanced Engineering Concepts
Python lists are implemented as dynamic arrays (similar to std::vector in C++). When a list is full, Python allocates a new, larger array and copies the pointers over. This means append() operations are O(1) amortized, but insert(0) is O(N) because all elements must be shifted. Strings, being immutable, require allocating a completely new string object for any modification (like concatenation).
Code Implementation
# Memory efficiency demonstration
import sys
lst = []
for i in range(10):
print(f"Length: {len(lst)}, Size in bytes: {sys.getsizeof(lst)}")
lst.append(i)
# String immutability
s1 = "BTech"
s2 = s1
s1 += " Python"
print(f"s1 id: {id(s1)}, s2 id: {id(s2)}") # Different IDs