1

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 :)

user3043893
  • 311
  • 4
  • 12
  • I highly recommend reading [this article](http://robertheaton.com/2014/02/09/pythons-pass-by-object-reference-as-explained-by-philip-k-dick/) in its entirety. – Rick May 16 '15 at 00:00
  • See also one of [my old questions](http://stackoverflow.com/questions/26587683/understanding-python-name-objects-immutable-data-and-memory-management). Lots of good information in the comments there. – Rick May 16 '15 at 00:03

2 Answers2

3

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).

Dleep
  • 1,045
  • 5
  • 12
  • As strings are, as you said, immutable, you can't modify them. if you do something like this: a = "asd", b = a, b = "hohoho", a will still be "asd" – Dleep May 15 '15 at 23:45
  • Emiliano Sorbello, that's not unique to immutable objects at all. Try it with lists for example. – Navith May 16 '15 at 00:59
  • I know, i just tried to elaborate on my answer. if it didn't seem like that, srry, my english is a bit rough around the edges – Dleep May 16 '15 at 01:51
0

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
salparadise
  • 5,699
  • 1
  • 26
  • 32