When I pass a string to a function, does python copy the whole string to a new memory location or does it wait until I try to modify the string from inside the function?
Thanks :)
When I pass a string to a function, does python copy the whole string to a new memory location or does it wait until I try to modify the string from inside the function?
Thanks :)
Python has only 1 copy of each immutable object, no matter how many variables you have referring to it. When using said string as an argument to another function, you're only passing that reference to it. When you say "modify" what happens is python just changes that reference (also creating the new string if it wasn't used arleady, and eventually deleting the old one it's not referenced anywhere else).
Passed by reference (and you have to use global to change it inside the function per scope rules):
In [31]: def t():
....: global s
....: print id(s)
....: s = 'foo'
....: print id(s)
....:
In [36]: s = 'spam'
In [37]: id(s)
Out[37]: 4471963392
In [38]: t()
4471963392
4467742200