0
spam = "woo"
eggs = spam
spam = "string"
print eggs
# prints woo

However for array, it is different:

import numpy
# The coefficients for the Taylor polynomial for exp(x)
Taylor_coefficients = numpy.array(
[1.0, 0.5, 0.1666, 0.04164, 0.0083, 0.0014])
coeff = Taylor_coefficients
coeff[1] = 0
print Taylor_coefficients[:2]
# prints [ 1.  0.]

What happens here, and which other common datatypes than array does this apply to?

John Kugelman
  • 330,190
  • 66
  • 504
  • 555
Mikkel Rev
  • 769
  • 3
  • 11
  • 30
  • 2
    This has (almost) nothing to do with strings versus arrays. It has to do with plain assignment versus item assignment (`a[b] = c`). –  Dec 14 '13 at 17:33
  • (The possible duplicate speaks of function arguments, but assignment behaves exactly the same way.) –  Dec 14 '13 at 17:40

1 Answers1

-1

This difference in behavior is due to the difference between mutable and immutable objects. Read the wiki page for more information on python types.

When you spam = "string", spam is pointed to a new location with a new string, because strings are immutable (cannot be changed after creation), which leaves eggs in-tact, pointing to the old string. But for arrays (or other mutable objects), coff = Taylor_coefficients will point to the same object, and changing that object will reflect in all references to it.

micromoses
  • 4,838
  • 1
  • 18
  • 23