-4

I don't understand why in this example, using the .lower() method won't change the string without assignment, but the .reverse() method changes the list without assignment. Do certain data types need assignment to change, and others don't? Why? Thanks.

a = "ABC"
a.lower()

b = [1, 2, 3]
b.reverse()

print(a)
print(b)
Pyro
  • 11
  • 1
  • 2
    Because strings are *immutable*, but lists are *mutable*. – jonrsharpe Feb 27 '15 at 18:56
  • You cannot alter a string object, full stop. You always have to replace the bound name to point to a new string object. – Martijn Pieters Feb 27 '15 at 18:57
  • Also, some methods don't change their objects, even if those objects are mutable. – Scott Hunter Feb 27 '15 at 18:58
  • This shouldn be downvoted. There's no way someone could find the "original' question if he is asking what the OP did. If someone did it would be because he already knew the answer. It is good to redirect to that one, but this question should be promoted as it has been done. – Martin Nov 18 '18 at 17:49

1 Answers1

1

Do certain data types need assignment to change, and others don't?

Yes.

Why?

Because that is part of the API provided by each type.

Some types of objects (like lists) provide ways of mutating their data (like list.reverse). Others don't. That's just part of what you need to know about a type in order to use it effectively. In Python parlance, types that allow such mutation are called "mutable" and ones that don't are "immutable".

(Technically, in your example above, you never "change" the string. Rather, you create a new string and assign it to the variable that used to point at the old string. This is different from important ways from your list example, where the actual list object is altered. You can find lots of information about the differences by searching for discussions of mutable vs. immutable objects.)

BrenBarn
  • 242,874
  • 37
  • 412
  • 384