I am from c background and a beginner in python. I want to know how strings are actually stored in memory in case of python.
I did something like
s="foo"id(s)=140542718184424id(s[0])= 140542719027040
id(s[1])= 140542718832152
id(s[2])= 140542718832152
I did not understand how each character is getting stored in memory and and why id of s is not equal to id of s[0] (like it use to be in c) and why id of s1 and s2 are same?
Python has no characters. Indexing into a string creates a new string, which (like every other object) promptly vanquishes if you don't keep a reference to it around. So the id()
s in your example can't be compared with each other, an object's id is only unique as long as the object lives. In particular, id(s[0]) != id(s)
because the former is a new (temporary) object, and id(s[1]) == id(s[2])
because after the first operand is evaluated, the first temporary string is destroyed and the second temporary string is allocated to the previously freed memory. The latter is an implementation detail and a coincidence and cannot be relied on.
Reasoning about string memory is further complicated by implementation details like small strings (along with integers, some tuples, and more) being interned, so some_str is other_str
may be true for equal strings that come from different sources (e.g. from indexing into a string with different indices).