I was trying to make the connection between python string and C character array assignment to string literals.
For example:
char* word="Hello";
word="Now";
assigns to the character String “Hello” placed in read only memory location. And now a reassignment of word to “Now” means a now the character array is assigned a memory location corresponding to “Now”.
In python even numbers (and obviously strings) seem to work like that with a being assigned a memory location with value 2 and then reassigned a memory location with value 3.
a=2
a=3
This contrasts with C where for almost all variable assignments the variable contains the value it is assigned. Am I making a good comparison here?
In C,
char *is the type “pointer to character.” A pointer is like a “handle” that gives you access to the value itself. When you assignword = "Now";, you are changing the handle, not the characters of the string. Both"Hello"and"Now"still exist as groups of bytes in constant storage.Python hides more of what it’s doing, but internally its built-in string references essentially act like pointers. So your observation is correct up to a point.
The big difference in strings of these languages is that in Python all strings are immutable. C lets you manipulate (by assignment) characters within a (non-constant) string. For example:
In Python, you would have to create a completely new string:
Here the bytes that make up the new string are different than those of
word.You are right that Python has “reference semantics”. Everything behaves as though you are manipulating a handle rather than a value.
Here the assignment
b = acopied a handle or reference to the list. The list itself is not copied. This is evident because changing the first element ofaalso changedb.